refactor: migrate to props and runes

this was done using sv migrate and a bit of ai to fully migrate
This commit is contained in:
2026-04-24 01:12:33 -04:00
parent 2864c81f83
commit 9064aecedb
17 changed files with 463 additions and 326 deletions
@@ -4,28 +4,41 @@
label: string; label: string;
} }
export let options: Option[] = []; interface Props {
export let value: string | number = ''; options?: Option[];
export let placeholder = 'Select...'; value?: string | number;
export let searchable = false; placeholder?: string;
export let displayValue: (val: string | number) => string = (val) => { searchable?: boolean;
displayValue?: (val: string | number) => string;
variant?: string;
}
let {
options = [],
value = $bindable(''),
placeholder = 'Select...',
searchable = false,
displayValue = (val) => {
return options.find((o) => o.value === val)?.label ?? String(val); return options.find((o) => o.value === val)?.label ?? String(val);
}; },
export let variant: string = ''; variant = ''
}: Props = $props();
let isOpen = false; let isOpen = $state(false);
let searchQuery = ''; let searchQuery = $state('');
let dropdownElement: HTMLDivElement; let dropdownElement = $state<HTMLDivElement | undefined>(undefined);
let dropdownListElement: HTMLDivElement; let dropdownListElement = $state<HTMLDivElement | undefined>(undefined);
let dropdownMaxHeight = '12rem'; let dropdownMaxHeight = $state('12rem');
$: filteredOptions = searchable let filteredOptions = $derived(
searchable
? options.filter( ? options.filter(
(opt) => (opt) =>
opt.label.toLowerCase().includes(searchQuery.toLowerCase()) || opt.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
String(opt.value).toLowerCase().includes(searchQuery.toLowerCase()) String(opt.value).toLowerCase().includes(searchQuery.toLowerCase())
) )
: options; : options
);
function handleSelect(selectedValue: string | number) { function handleSelect(selectedValue: string | number) {
value = selectedValue; value = selectedValue;
@@ -64,12 +77,12 @@
} }
</script> </script>
<svelte:window on:click={handleClickOutside} /> <svelte:window onclick={handleClickOutside} />
<div bind:this={dropdownElement} class="relative mb-2 w-full" class:dropdown-sm={variant === 'sm'}> <div bind:this={dropdownElement} class="relative mb-2 w-full" class:dropdown-sm={variant === 'sm'}>
<button <button
type="button" type="button"
on:click={toggleDropdown} onclick={toggleDropdown}
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-left transition-colors hover:bg-neutral-700" class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-left transition-colors hover:bg-neutral-700"
class:dropdown-sm-btn={variant === 'sm'} class:dropdown-sm-btn={variant === 'sm'}
> >
@@ -91,7 +104,7 @@
class="w-full border-b border-neutral-700 bg-neutral-800 p-2 outline-none" class="w-full border-b border-neutral-700 bg-neutral-800 p-2 outline-none"
class:dropdown-sm-input={variant === 'sm'} class:dropdown-sm-input={variant === 'sm'}
bind:value={searchQuery} bind:value={searchQuery}
on:keydown={handleKeyDown} onkeydown={handleKeyDown}
/> />
</div> </div>
{/if} {/if}
@@ -102,7 +115,7 @@
{#each filteredOptions as option (option.value)} {#each filteredOptions as option (option.value)}
<button <button
type="button" type="button"
on:click={() => handleSelect(option.value)} onclick={() => handleSelect(option.value)}
class="w-full border-b border-neutral-700 px-3 py-2 text-left last:border-b-0 hover:bg-neutral-600" class="w-full border-b border-neutral-700 px-3 py-2 text-left last:border-b-0 hover:bg-neutral-600"
class:bg-neutral-700={value === option.value} class:bg-neutral-700={value === option.value}
class:dropdown-sm-option={variant === 'sm'} class:dropdown-sm-option={variant === 'sm'}
@@ -5,8 +5,9 @@
import { tick } from 'svelte'; import { tick } from 'svelte';
import { extractError } from '$lib/utils/misc'; import { extractError } from '$lib/utils/misc';
export let show = false; interface Props {
export let mode: show?: boolean;
mode?:
| 'decrypt' | 'decrypt'
| 'encrypt' | 'encrypt'
| 'confirm' | 'confirm'
@@ -14,37 +15,58 @@
| 'multiselect' | 'multiselect'
| 'totp' | 'totp'
| 'totpSetup' | 'totpSetup'
| 'report' = 'decrypt'; | 'report';
export let title = ''; title?: string;
export let message = ''; message?: string;
export let error = ''; error?: string;
export let placeholder = ''; placeholder?: string;
export let inputType = 'text'; inputType?: string;
export let inputMaxLength: number | null = null; inputMaxLength?: number | null;
export let items: { label: string; value: unknown }[] = []; items?: { label: string; value: unknown }[];
export let initialValue: unknown = null; initialValue?: unknown;
export let totpActive: boolean | null = null; totpActive?: boolean | null;
export let reportTarget: 'user' | 'paste' | null = null; reportTarget?: 'user' | 'paste' | null;
export let reportTargetId: string | number | null = null; reportTargetId?: string | number | null;
export let reportSiteKey: string | null = null; reportSiteKey?: string | null;
export let onConfirm: (value: unknown) => void; onConfirm: (value: unknown) => void;
export let onCancel: () => void; onCancel: () => void;
export let confirmButtonText = ''; confirmButtonText?: string;
}
let inputValue: string | unknown[] | boolean = ''; let {
let totpSecret = ''; show = false,
let totpQr = ''; mode = 'decrypt',
let totpEnabled = false; title = '',
let totpInitialized = false; message = '',
let totpLoading = false; error = $bindable(''),
let totpError = ''; placeholder = '',
let displayError = ''; inputType = 'text',
let reportTypes: string[] = []; inputMaxLength = null,
let reportType = ''; items = [],
let reportInitialized = false; initialValue = null,
let reportLoading = false; totpActive = null,
let multiselectInitialized = false; reportTarget = null,
let turnstileEl: HTMLDivElement | null = null; reportTargetId = null,
reportSiteKey = null,
onConfirm,
onCancel,
confirmButtonText = ''
}: Props = $props();
let inputValue: string | unknown[] | boolean = $state('');
let totpSecret = $state('');
let totpQr = $state('');
let totpEnabled = $state(false);
let totpInitialized = $state(false);
let totpLoading = $state(false);
let totpError = $state('');
let displayError = $derived(error || totpError);
let reportTypes: string[] = $state([]);
let reportType = $state('');
let reportInitialized = $state(false);
let reportLoading = $state(false);
let multiselectInitialized = $state(false);
let turnstileEl: HTMLDivElement | null = $state(null);
let turnstileWidgetId: string | null = null; let turnstileWidgetId: string | null = null;
const titleMap = { const titleMap = {
@@ -63,34 +85,12 @@
encrypt: 'Encrypt', encrypt: 'Encrypt',
confirm: 'Confirm', confirm: 'Confirm',
multiselect: 'Confirm', multiselect: 'Confirm',
totpSetup: totpEnabled ? 'Disable' : 'Enable', totpSetup: 'Enable',
totp: 'Verify', totp: 'Verify',
report: 'Submit Report', report: 'Submit Report',
prompt: 'Submit' prompt: 'Submit'
}; };
$: displayError = error || totpError;
$: if (!show) resetModal();
$: if (show && mode === 'totpSetup' && !totpInitialized) {
totpInitialized = true;
if (totpActive !== null) {
totpEnabled = totpActive;
}
initializeTotp();
}
$: if (show && mode === 'report' && !reportInitialized) {
reportInitialized = true;
initializeReport();
}
$: if (show && mode === 'multiselect' && !multiselectInitialized) {
multiselectInitialized = true;
inputValue = Array.isArray(initialValue) ? JSON.parse(JSON.stringify(initialValue)) : [];
}
function resetModal() { function resetModal() {
inputValue = inputValue =
initialValue !== null initialValue !== null
@@ -212,7 +212,8 @@
return null; return null;
} }
async function handleSubmit() { async function handleSubmit(event: Event) {
event.preventDefault();
if (mode === 'report') { if (mode === 'report') {
await submitReport(); await submitReport();
return; return;
@@ -394,17 +395,44 @@
} }
} }
$: displayTitle = title || titleMap[mode]; $effect(() => {
if (!show) resetModal();
$: confirmLabel = confirmButtonText || confirmLabelMap[mode]; });
$: shouldShowInput = $effect(() => {
mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup' && mode !== 'report'; if (show && mode === 'totpSetup' && !totpInitialized) {
totpInitialized = true;
if (totpActive !== null) {
totpEnabled = totpActive;
}
initializeTotp();
}
});
$effect(() => {
if (show && mode === 'report' && !reportInitialized) {
reportInitialized = true;
initializeReport();
}
});
$effect(() => {
if (show && mode === 'multiselect' && !multiselectInitialized) {
multiselectInitialized = true;
inputValue = Array.isArray(initialValue) ? JSON.parse(JSON.stringify(initialValue)) : [];
}
});
let displayTitle = $derived(title || titleMap[mode]);
let confirmLabel = $derived(
confirmButtonText ||
(mode === 'totpSetup' ? (totpEnabled ? 'Disable' : 'Enable') : confirmLabelMap[mode])
);
let shouldShowInput = $derived(
mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup' && mode !== 'report'
);
</script> </script>
{#if show} {#if show}
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-xs"> <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-xs">
<form <form
on:submit|preventDefault={handleSubmit} onsubmit={handleSubmit}
class="w-full max-w-md rounded border border-neutral-800 bg-neutral-900 p-6" class="w-full max-w-md rounded border border-neutral-800 bg-neutral-900 p-6"
> >
<h2 class="mb-4 text-xl font-semibold text-white"> <h2 class="mb-4 text-xl font-semibold text-white">
@@ -448,7 +476,7 @@
> >
<button <button
type="button" type="button"
on:click={copySecret} onclick={copySecret}
class="rounded bg-neutral-700 px-3 py-1 text-sm font-medium text-white transition-colors hover:bg-neutral-800" class="rounded bg-neutral-700 px-3 py-1 text-sm font-medium text-white transition-colors hover:bg-neutral-800"
> >
Copy Copy
@@ -463,7 +491,7 @@
maxlength="6" maxlength="6"
inputmode="numeric" inputmode="numeric"
pattern="[0-9]*" pattern="[0-9]*"
on:input={onCodeInput} oninput={onCodeInput}
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none" class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
/> />
{/if} {/if}
@@ -543,7 +571,7 @@
</button> </button>
<button <button
type="button" type="button"
on:click={onCancel} onclick={onCancel}
class="cursor-pointer rounded border border-neutral-700 px-4 py-2 text-white hover:bg-neutral-950" class="cursor-pointer rounded border border-neutral-700 px-4 py-2 text-white hover:bg-neutral-950"
> >
Cancel Cancel
@@ -2,7 +2,7 @@
import Modal from '$lib/components/Modal.svelte'; import Modal from '$lib/components/Modal.svelte';
import { cancelModal, confirmModal, modal } from '$lib/stores/modal'; import { cancelModal, confirmModal, modal } from '$lib/stores/modal';
$: state = $modal; let state = $derived($modal);
</script> </script>
<Modal <Modal
@@ -15,9 +15,13 @@
window.location.href = '/'; window.location.href = '/';
} }
export let data: PageData; interface Props {
data: PageData;
}
let menuOpen = false; let { data }: Props = $props();
let menuOpen = $state(false);
let currentPath = page.url.pathname; let currentPath = page.url.pathname;
let returnParam = let returnParam =
@@ -73,7 +77,7 @@
>Profile</a >Profile</a
> >
<button <button
on:click={logout} onclick={logout}
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600" class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
>Logout</button >Logout</button
> >
@@ -104,7 +108,7 @@
</a> </a>
<button <button
class="ml-auto flex h-10 w-10 items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 hover:bg-neutral-700 focus:outline-none" class="ml-auto flex h-10 w-10 items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 hover:bg-neutral-700 focus:outline-none"
on:click={() => (menuOpen = !menuOpen)} onclick={() => (menuOpen = !menuOpen)}
aria-label="Toggle Menu" aria-label="Toggle Menu"
aria-expanded={menuOpen} aria-expanded={menuOpen}
> >
@@ -126,23 +130,23 @@
<a <a
href={resolve('/recent')} href={resolve('/recent')}
class="block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700" class="block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
on:click={() => (menuOpen = false)}>Recent Pastes</a onclick={() => (menuOpen = false)}>Recent Pastes</a
> >
{#if $user} {#if $user}
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)} {#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
<a <a
href={resolve('/reports')} href={resolve('/reports')}
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700" class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
on:click={() => (menuOpen = false)}>Reports</a onclick={() => (menuOpen = false)}>Reports</a
> >
{/if} {/if}
<a <a
href={resolve(`/user/${$user.username}`)} href={resolve(`/user/${$user.username}`)}
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700" class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
on:click={() => (menuOpen = false)}>Profile</a onclick={() => (menuOpen = false)}>Profile</a
> >
<button <button
on:click={() => { onclick={() => {
logout(); logout();
menuOpen = false; menuOpen = false;
}} }}
@@ -153,7 +157,7 @@
<a <a
href={resolve(`/login${returnParam}`)} href={resolve(`/login${returnParam}`)}
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700" class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
on:click={() => (menuOpen = false)}>Login</a onclick={() => (menuOpen = false)}>Login</a
> >
<!-- eslint-disable svelte/no-navigation-without-resolve --> <!-- eslint-disable svelte/no-navigation-without-resolve -->
<a <a
@@ -162,7 +166,7 @@
.options?.registration_enabled .options?.registration_enabled
? '' ? ''
: 'cursor-not-allowed bg-neutral-900 text-neutral-500'}" : 'cursor-not-allowed bg-neutral-900 text-neutral-500'}"
on:click={() => (menuOpen = false)}>Register</a onclick={() => (menuOpen = false)}>Register</a
> >
<!-- eslint-enable svelte/no-navigation-without-resolve --> <!-- eslint-enable svelte/no-navigation-without-resolve -->
{/if} {/if}
@@ -17,12 +17,16 @@
import { syntaxes } from '$lib/consts'; import { syntaxes } from '$lib/consts';
import type { Paste } from '$lib/types/paste'; import type { Paste } from '$lib/types/paste';
export let paste: Paste; interface Props {
export let now: Date; paste: Paste;
export let showUser: boolean = true; now: Date;
export let compact: boolean = false; showUser?: boolean;
compact?: boolean;
}
const syntax = syntaxes[paste.syntax] ?? syntaxes['plaintext']; let { paste, now, showUser = true, compact = false }: Props = $props();
let syntax = $derived(syntaxes[paste.syntax] ?? syntaxes['plaintext']);
</script> </script>
{#if compact} {#if compact}
@@ -10,11 +10,15 @@
import User from '@lucide/svelte/icons/user'; import User from '@lucide/svelte/icons/user';
import type { PasteEmbedProps } from './pasteEmbed'; import type { PasteEmbedProps } from './pasteEmbed';
export let title: PasteEmbedProps['title']; interface Props {
export let uploader: PasteEmbedProps['uploader']; title: PasteEmbedProps['title'];
export let metadata: PasteEmbedProps['metadata']; uploader: PasteEmbedProps['uploader'];
export let previewLines: PasteEmbedProps['previewLines']; metadata: PasteEmbedProps['metadata'];
export let isEncrypted: PasteEmbedProps['isEncrypted']; previewLines: PasteEmbedProps['previewLines'];
isEncrypted: PasteEmbedProps['isEncrypted'];
}
let { title, uploader, metadata, previewLines, isEncrypted }: Props = $props();
const metadataIcons = { const metadataIcons = {
size: FileBox, size: FileBox,
+2 -1
View File
@@ -69,7 +69,8 @@ function parseBooleanClaim(value: unknown) {
} }
function parseNumberClaim(value: unknown): number | null { function parseNumberClaim(value: unknown): number | null {
const numeric = typeof value === 'number' ? value : typeof value === 'string' ? parseInt(value, 10) : NaN; const numeric =
typeof value === 'number' ? value : typeof value === 'string' ? parseInt(value, 10) : NaN;
return Number.isFinite(numeric) ? numeric : null; return Number.isFinite(numeric) ? numeric : null;
} }
+7 -2
View File
@@ -11,7 +11,12 @@
import { page } from '$app/state'; import { page } from '$app/state';
import type { LayoutData } from './$types'; import type { LayoutData } from './$types';
export let data: LayoutData; interface Props {
data: LayoutData;
children?: import('svelte').Snippet;
}
let { data, children }: Props = $props();
async function syncUserFromToken() { async function syncUserFromToken() {
const token = getToken(); const token = getToken();
@@ -103,7 +108,7 @@
</svelte:head> </svelte:head>
<Navbar {data} /> <Navbar {data} />
<slot /> {@render children?.()}
<Footer /> <Footer />
<ModalHost /> <ModalHost />
+53 -39
View File
@@ -18,37 +18,47 @@
import { SvelteURLSearchParams } from 'svelte/reactivity'; import { SvelteURLSearchParams } from 'svelte/reactivity';
import { FileUp, X, Eye, EyeClosed, Dices } from '@lucide/svelte'; import { FileUp, X, Eye, EyeClosed, Dices } from '@lucide/svelte';
export let data: PageData; interface Props {
data: PageData;
}
let textArea: HTMLTextAreaElement; let { data }: Props = $props();
let markdownConatiner: HTMLDivElement;
let error = ''; let textArea = $state<HTMLTextAreaElement | undefined>(undefined);
let title = ''; let markdownConatiner = $state<HTMLDivElement | undefined>(undefined);
let content = '';
let selectedSyntax = data.options?.syntaxes?.[0];
let expiresIn: number = 0;
let selectedVisibility = data.options?.visibilities?.[0]?.value;
let password = '';
let passwordVisible = false;
let anonymousUpload = false;
let isDragging = false;
let dragError = '';
let previewMode = false;
let renderedMarkdown = '';
$: currentByteSize = const getInitialSyntax = () => data.options?.syntaxes?.[0] ?? 'plaintext';
const getInitialVisibility = () => data.options?.visibilities?.[0]?.value ?? 0;
let error = $state('');
let title = $state('');
let content = $state('');
let selectedSyntax = $state(getInitialSyntax());
let expiresIn: number = $state(0);
let selectedVisibility = $state(getInitialVisibility());
let password = $state('');
let passwordVisible = $state(false);
let anonymousUpload = $state(false);
let isDragging = $state(false);
let dragError = $state('');
let previewMode = $state(false);
let renderedMarkdown = $state('');
let currentByteSize = $derived(
selectedVisibility === 2 selectedVisibility === 2
? estimateEncryptedSize(content) ? estimateEncryptedSize(content)
: new TextEncoder().encode(content).length; : new TextEncoder().encode(content).length
);
$: if (selectedSyntax !== 'markdown') { $effect(() => {
if (selectedSyntax !== 'markdown') {
previewMode = false; previewMode = false;
} }
});
const MAX_HEIGHT = () => Math.floor((window.innerHeight - 120) * 0.6); const MAX_HEIGHT = () => Math.floor((window.innerHeight - 120) * 0.6);
let previewHeight = 'auto'; let previewHeight = $state('auto');
async function togglePreview(toPreview: boolean) { async function togglePreview(toPreview: boolean) {
if (toPreview && !previewMode) { if (toPreview && !previewMode) {
previewHeight = textArea?.style.height || 'auto'; previewHeight = textArea?.style.height || 'auto';
@@ -59,11 +69,11 @@
} }
function resize(markdown: boolean = false) { function resize(markdown: boolean = false) {
if ((!markdown && !textArea) || (markdown && !markdownConatiner)) return; const element = markdown ? markdownConatiner : textArea;
if (!element) return;
let h: number; let h: number;
let max: number; let max: number;
let element = markdown ? markdownConatiner : textArea;
element.style.height = 'auto'; element.style.height = 'auto';
h = element.scrollHeight; h = element.scrollHeight;
@@ -106,17 +116,21 @@
}; };
}); });
const syntaxOptions = let syntaxOptions = $derived.by(
() =>
data.options?.syntaxes?.map((lang: string) => ({ data.options?.syntaxes?.map((lang: string) => ({
value: lang, value: lang,
label: syntaxes[lang]?.name ?? lang.charAt(0).toUpperCase() + lang.slice(1) label: syntaxes[lang]?.name ?? lang.charAt(0).toUpperCase() + lang.slice(1)
})) ?? []; })) ?? []
);
const visibilityOptions = let visibilityOptions = $derived.by(
() =>
data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({ data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
value: visibility.value, value: visibility.value,
label: visibility.displayName label: visibility.displayName
})) ?? []; })) ?? []
);
async function handleSubmit(event: Event) { async function handleSubmit(event: Event) {
event.preventDefault(); event.preventDefault();
@@ -244,7 +258,7 @@
> >
<div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6"> <div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1> <h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1>
<form class="mt-4" on:submit|preventDefault={handleSubmit}> <form class="mt-4" onsubmit={handleSubmit}>
<input <input
type="text" type="text"
placeholder="Title (optional)" placeholder="Title (optional)"
@@ -274,10 +288,10 @@
minlength="1" minlength="1"
bind:this={textArea} bind:this={textArea}
bind:value={content} bind:value={content}
on:input={() => resize()} oninput={() => resize()}
on:change={() => resize()} onchange={() => resize()}
on:focus={() => resize()} onfocus={() => resize()}
on:beforeinput={(e) => { onbeforeinput={(e) => {
if (!data.options?.maxPasteSize) return; if (!data.options?.maxPasteSize) return;
const futureSize = const futureSize =
@@ -292,19 +306,19 @@
e.preventDefault(); e.preventDefault();
} }
}} }}
on:dragenter={(e) => { ondragenter={(e) => {
e.preventDefault(); e.preventDefault();
isDragging = true; isDragging = true;
}} }}
on:dragover={(e) => { ondragover={(e) => {
e.preventDefault(); e.preventDefault();
isDragging = true; isDragging = true;
}} }}
on:dragleave={(e) => { ondragleave={(e) => {
e.preventDefault(); e.preventDefault();
isDragging = false; isDragging = false;
}} }}
on:drop={(e) => { ondrop={(e) => {
requestAnimationFrame(() => resize()); requestAnimationFrame(() => resize());
e.preventDefault(); e.preventDefault();
isDragging = false; isDragging = false;
@@ -376,7 +390,7 @@
class="h-full w-1/2 rounded-l transition-colors {previewMode class="h-full w-1/2 rounded-l transition-colors {previewMode
? 'hover:bg-neutral-700' ? 'hover:bg-neutral-700'
: 'bg-neutral-700 text-white'}" : 'bg-neutral-700 text-white'}"
on:click={() => togglePreview(false)} onclick={() => togglePreview(false)}
> >
Code Code
</button> </button>
@@ -385,7 +399,7 @@
class="h-full w-1/2 rounded-r transition-colors {!previewMode class="h-full w-1/2 rounded-r transition-colors {!previewMode
? 'hover:bg-neutral-700' ? 'hover:bg-neutral-700'
: 'bg-neutral-700 text-white'}" : 'bg-neutral-700 text-white'}"
on:click={() => togglePreview(true)} onclick={() => togglePreview(true)}
> >
Preview Preview
</button> </button>
@@ -449,7 +463,7 @@
<button <button
type="button" type="button"
class="mr-1 ml-1 flex w-12.5 items-center justify-center border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600" class="mr-1 ml-1 flex w-12.5 items-center justify-center border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
on:click={() => { onclick={() => {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const bytes = new Uint8Array(16); const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes); crypto.getRandomValues(bytes);
@@ -462,7 +476,7 @@
<button <button
type="button" type="button"
class="flex w-12.5 items-center justify-center rounded-r border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600" class="flex w-12.5 items-center justify-center rounded-r border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
on:click={() => (passwordVisible = !passwordVisible)} onclick={() => (passwordVisible = !passwordVisible)}
> >
{#if passwordVisible} {#if passwordVisible}
<EyeClosed class="h-5 w-5" /> <EyeClosed class="h-5 w-5" />
+41 -33
View File
@@ -49,33 +49,41 @@
import { openModal } from '$lib/stores/modal'; import { openModal } from '$lib/stores/modal';
import type { Paste } from '$lib/types/paste'; import type { Paste } from '$lib/types/paste';
import HighlightWorker from '$lib/workers/highlight.worker?worker'; import HighlightWorker from '$lib/workers/highlight.worker?worker';
export let data: PageData; interface Props {
data: PageData;
}
let reportSiteKey: string | null = null; let { data = $bindable() }: Props = $props();
let editing = false;
let editContent: string | null = null; let reportSiteKey = $derived(
let editMetadata: Paste | null = data.paste ? { ...data.paste } : null; (data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
let editError = ''; ?.cf_turnstile_site_key ?? null
let editLoading = false; );
let isBinary = false; let editing = $state(false);
let pasteContent = ''; let editContent: string | null = $state(null);
let decryptedContent: string | null = null; let editMetadata: Paste | null = $state(data.paste ? { ...data.paste } : null);
let editError = $state('');
let editLoading = $state(false);
let isBinary = $state(false);
let pasteContent = $state('');
let decryptedContent: string | null = $state(null);
let decryptError = ''; let decryptError = '';
let decryptStatus = ''; let decryptStatus = $state('');
let contentRendered = false; let contentRendered = $state(false);
let downloadedPaste = false; let downloadedPaste = $state(false);
let copiedPaste = false; let copiedPaste = $state(false);
let highlightWorker: Worker | null = null; let highlightWorker: Worker | null = null;
let highlightRequestId = 0; let highlightRequestId = 0;
let ignoreExternalMediaWarning = false; let ignoreExternalMediaWarning = false;
let scrollY = 0; let scrollY = $state(0);
let now = new Date(); let now = $state(new Date());
$: isExpired = let isExpired = $derived(
data?.paste?.expiresAt && data.paste.expiresAt !== 0 data?.paste?.expiresAt && data.paste.expiresAt !== 0
? new Date(data.paste.expiresAt).getTime() <= now.getTime() ? new Date(data.paste.expiresAt).getTime() <= now.getTime()
: false; : false
);
let interval: ReturnType<typeof setInterval> | null = null; let interval: ReturnType<typeof setInterval> | null = null;
@@ -490,12 +498,12 @@
} }
}); });
$: if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderPaste(); $effect(() => {
$: reportSiteKey = if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderPaste();
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions });
?.cf_turnstile_site_key ?? null; let pasteImageUrl = $derived(
$: pasteImageUrl = data?.paste && data?.url ? `${new URL(data.url).origin}/${data.paste.id}.jpg` : null
data?.paste && data?.url ? `${new URL(data.url).origin}/${data.paste.id}.jpg` : null; );
</script> </script>
<svelte:window bind:scrollY /> <svelte:window bind:scrollY />
@@ -750,7 +758,7 @@
<button <button
type="button" type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600" class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => { onclick={() => {
navigator.clipboard.writeText(decryptedContent ?? data.content); navigator.clipboard.writeText(decryptedContent ?? data.content);
copiedPaste = true; copiedPaste = true;
setTimeout(() => (copiedPaste = false), 1000); setTimeout(() => (copiedPaste = false), 1000);
@@ -778,7 +786,7 @@
<button <button
type="button" type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600" class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => { onclick={() => {
const blob = new Blob([decryptedContent ?? data.content], { const blob = new Blob([decryptedContent ?? data.content], {
type: 'text/plain' type: 'text/plain'
}); });
@@ -839,7 +847,7 @@
<button <button
type="button" type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-amber-600/50" class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-amber-600/50"
on:click={() => { onclick={() => {
promptUser('report'); promptUser('report');
}} }}
> >
@@ -853,7 +861,7 @@
<button <button
type="button" type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600" class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => { onclick={() => {
editContent = decryptedContent ?? data.content; editContent = decryptedContent ?? data.content;
editError = ''; editError = '';
editing = true; editing = true;
@@ -866,7 +874,7 @@
<button <button
type="button" type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-red-900" class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-red-900"
on:click={() => { onclick={() => {
promptUser('confirm').then(async (value) => { promptUser('confirm').then(async (value) => {
if (value) { if (value) {
const token = getToken(); const token = getToken();
@@ -895,7 +903,7 @@
<button <button
type="button" type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600" class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={async () => { onclick={async () => {
if (editContent !== null || editMetadata !== null) { if (editContent !== null || editMetadata !== null) {
await updatePaste(editContent, editMetadata); await updatePaste(editContent, editMetadata);
} }
@@ -908,7 +916,7 @@
<button <button
type="button" type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600" class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => { onclick={() => {
editing = false; editing = false;
editError = ''; editError = '';
}} }}
@@ -922,7 +930,7 @@
<button <button
transition:fade={{ duration: 200 }} transition:fade={{ duration: 200 }}
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600" class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => window.scrollTo({ top: 0, behavior: 'smooth' })} onclick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
aria-label="Scroll to top" aria-label="Scroll to top"
> >
<ArrowUp class="mr-1 h-5 w-5 text-neutral-400" /> <ArrowUp class="mr-1 h-5 w-5 text-neutral-400" />
@@ -963,7 +971,7 @@
? 'csv-container scrollbar overflow-x-auto overflow-y-auto scrollbar-thumb-neutral-600 scrollbar-track-neutral-800' ? 'csv-container scrollbar overflow-x-auto overflow-y-auto scrollbar-thumb-neutral-600 scrollbar-track-neutral-800'
: 'codeblock-with-lines overflow-x-auto overflow-y-auto'} : 'codeblock-with-lines overflow-x-auto overflow-y-auto'}
class:hidden={!contentRendered} class:hidden={!contentRendered}
on:click={handleMarkdownClick} onclick={handleMarkdownClick}
role="presentation" role="presentation"
> >
<!-- eslint-disable-next-line svelte/no-at-html-tags --> <!-- eslint-disable-next-line svelte/no-at-html-tags -->
@@ -5,12 +5,16 @@
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import type { PageData } from './$types'; import type { PageData } from './$types';
let username = ''; let username = $state('');
let password = ''; let password = $state('');
let error = ''; let error = $state('');
let totpEnabled = false; let totpEnabled = $state(false);
let totpCode = ''; let totpCode = $state('');
export let data: PageData; interface Props {
data: PageData;
}
let { data }: Props = $props();
onMount(() => { onMount(() => {
const render = () => { const render = () => {
@@ -35,7 +39,8 @@
}; };
}); });
async function login() { async function login(event: Event) {
event.preventDefault();
const body: { username: string; password: string; token?: string; totpcode?: string } = { const body: { username: string; password: string; token?: string; totpcode?: string } = {
username, username,
password password
@@ -96,7 +101,7 @@
> >
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6"> <div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-3xl font-bold">Login</h1> <h1 class="mb-6 text-center text-3xl font-bold">Login</h1>
<form on:submit|preventDefault={login} class="space-y-4"> <form onsubmit={login} class="space-y-4">
<input <input
type="text" type="text"
placeholder="Username" placeholder="Username"
@@ -122,7 +127,7 @@
inputmode="numeric" inputmode="numeric"
pattern="[0-9]*" pattern="[0-9]*"
required required
on:input={(e) => { oninput={(e) => {
if (e.target instanceof HTMLInputElement) { if (e.target instanceof HTMLInputElement) {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6); e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
totpCode = e.target.value; totpCode = e.target.value;
@@ -3,9 +3,13 @@
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import Paste from '$lib/components/Paste.svelte'; import Paste from '$lib/components/Paste.svelte';
export let data: PageData; interface Props {
data: PageData;
}
let now = new Date(); let { data }: Props = $props();
let now = $state(new Date());
onMount(() => { onMount(() => {
const interval = setInterval(() => { const interval = setInterval(() => {
@@ -8,27 +8,31 @@
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import type { PageData } from './$types'; import type { PageData } from './$types';
let username = ''; let username = $state('');
let password = ''; let password = $state('');
let confirmPassword = ''; let confirmPassword = $state('');
let email = ''; let email = $state('');
let displayName = ''; let displayName = $state('');
let error = ''; let error = $state('');
let passwordFocused = false; let passwordFocused = $state(false);
let showPassword = false; let showPassword = $state(false);
let passwordChecks = { let passwordChecks = $state({
minLength: false, minLength: false,
maxLength: false, maxLength: false,
upper: false, upper: false,
lower: false, lower: false,
number: false number: false
}; });
let passwordValid = false; let passwordValid = $state(false);
let loading = false; let loading = $state(false);
export let data: PageData; interface Props {
data: PageData;
}
let { data }: Props = $props();
onMount(() => { onMount(() => {
const render = () => { const render = () => {
@@ -71,9 +75,12 @@
passwordChecks.number; passwordChecks.number;
} }
$: validatePassword(password); $effect(() => {
validatePassword(password);
});
async function register() { async function register(event: Event) {
event.preventDefault();
if (!passwordValid || password !== confirmPassword) return; if (!passwordValid || password !== confirmPassword) return;
loading = true; loading = true;
error = ''; error = '';
@@ -143,7 +150,7 @@
Registration is currently disabled. Registration is currently disabled.
</div> </div>
{/if} {/if}
<form on:submit|preventDefault={register} class="space-y-4"> <form onsubmit={register} class="space-y-4">
<input <input
type="text" type="text"
placeholder="Username" placeholder="Username"
@@ -179,15 +186,15 @@
placeholder="Password" placeholder="Password"
bind:value={password} bind:value={password}
required required
on:focus={() => (passwordFocused = true)} onfocus={() => (passwordFocused = true)}
on:blur={() => (passwordFocused = false)} onblur={() => (passwordFocused = false)}
autocomplete="new-password" autocomplete="new-password"
disabled={loading || !data.options?.registration_enabled} disabled={loading || !data.options?.registration_enabled}
class="focus:bg-neutral-750 w-[calc(100%-40px)] rounded-l border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600" class="focus:bg-neutral-750 w-[calc(100%-40px)] rounded-l border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/> />
<button <button
type="button" type="button"
on:click={() => (showPassword = !showPassword)} onclick={() => (showPassword = !showPassword)}
disabled={loading || !data.options?.registration_enabled} disabled={loading || !data.options?.registration_enabled}
class="ml-2 flex w-10 items-center rounded-r border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200 hover:bg-neutral-700 focus:outline-none" class="ml-2 flex w-10 items-center rounded-r border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200 hover:bg-neutral-700 focus:outline-none"
> >
@@ -5,15 +5,20 @@
import { tooltip } from '$lib/utils/misc'; import { tooltip } from '$lib/utils/misc';
import { getToken } from '$lib/utils/auth'; import { getToken } from '$lib/utils/auth';
export let data: PageData; interface Props {
data: PageData;
}
const report = data.report; let { data }: Props = $props();
let saving = false; const initialReport = () => ({ ...data.report });
let saveError = '';
const statusOptions = data.options?.statuses ?? []; let report = $state(initialReport());
const typeOptions = data.options?.types ?? []; let saving = $state(false);
let statusValue = reportStatusLabels[report.status] ?? ''; let saveError = $state('');
let typeValue = reportTypeLabels[report.type] ?? ''; let statusOptions = $derived(data.options?.statuses ?? []);
let typeOptions = $derived(data.options?.types ?? []);
let statusValue = $state(reportStatusLabels[report.status] ?? '');
let typeValue = $state(reportTypeLabels[report.type] ?? '');
async function updateReport() { async function updateReport() {
saveError = ''; saveError = '';
@@ -143,7 +148,7 @@
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<button <button
class="rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-60" class="rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-60"
on:click={updateReport} onclick={updateReport}
disabled={saving} disabled={saving}
> >
{saving ? 'Saving...' : 'Update Report'} {saving ? 'Saving...' : 'Update Report'}
@@ -1,4 +1,7 @@
<script lang="ts"> <script lang="ts">
import { createBubbler, stopPropagation } from 'svelte/legacy';
const bubble = createBubbler();
import type { PageData } from './$types'; import type { PageData } from './$types';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
@@ -6,14 +9,30 @@
import { tooltip } from '$lib/utils/misc'; import { tooltip } from '$lib/utils/misc';
import { SvelteURLSearchParams } from 'svelte/reactivity'; import { SvelteURLSearchParams } from 'svelte/reactivity';
export let data: PageData; interface Props {
data: PageData;
}
let target = data.filters.target; let { data }: Props = $props();
let status = data.filters.status; const initialFilters = (() => {
let type = data.filters.type ?? ''; const filters = data.filters;
let pasteId = data.filters.pasteId; return {
let userUuid = data.filters.userUuid; target: (filters.target as 'all' | 'pastes' | 'users') ?? 'all',
let mixedTarget = target === 'all' ? pasteId || userUuid : ''; status: filters.status ?? '',
type: filters.type ?? '',
pasteId: filters.pasteId ?? '',
userUuid: filters.userUuid ?? ''
};
})();
let target = $state(initialFilters.target);
let status = $state(initialFilters.status);
let type = $state(initialFilters.type);
let pasteId = $state(initialFilters.pasteId);
let userUuid = $state(initialFilters.userUuid);
let mixedTarget = $state(
initialFilters.target === 'all' ? initialFilters.pasteId || initialFilters.userUuid : ''
);
let inputTimer: ReturnType<typeof setTimeout> | null = null; let inputTimer: ReturnType<typeof setTimeout> | null = null;
const targets = [ const targets = [
@@ -22,8 +41,8 @@
{ value: 'users', label: 'Users' } { value: 'users', label: 'Users' }
]; ];
const statuses = data.options?.statuses ?? []; let statuses = $derived(data.options?.statuses ?? []);
const types = data.options?.types ?? []; let types = $derived(data.options?.types ?? []);
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function applyFilters(page = 1) { function applyFilters(page = 1) {
@@ -108,7 +127,7 @@
id="report-target" id="report-target"
class="rounded border border-neutral-700 bg-neutral-800 p-2" class="rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={target} bind:value={target}
on:change={(e) => { onchange={(e) => {
if (e.currentTarget instanceof HTMLSelectElement) { if (e.currentTarget instanceof HTMLSelectElement) {
handleTargetChange(e.currentTarget.value); handleTargetChange(e.currentTarget.value);
} }
@@ -125,7 +144,7 @@
id="report-status" id="report-status"
class="rounded border border-neutral-700 bg-neutral-800 p-2" class="rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={status} bind:value={status}
on:change={() => applyFilters(1)} onchange={() => applyFilters(1)}
> >
<option value="">Any</option> <option value="">Any</option>
{#each statuses as s (s)} {#each statuses as s (s)}
@@ -139,7 +158,7 @@
id="report-type" id="report-type"
class="rounded border border-neutral-700 bg-neutral-800 p-2" class="rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={type} bind:value={type}
on:change={() => applyFilters(1)} onchange={() => applyFilters(1)}
> >
<option value="">Any</option> <option value="">Any</option>
{#each types as t (t)} {#each types as t (t)}
@@ -165,7 +184,7 @@
? 'User UUID' ? 'User UUID'
: 'Paste ID or User UUID'} : 'Paste ID or User UUID'}
value={target === 'pastes' ? pasteId : target === 'users' ? userUuid : mixedTarget} value={target === 'pastes' ? pasteId : target === 'users' ? userUuid : mixedTarget}
on:input={(e) => { oninput={(e) => {
if (e.currentTarget instanceof HTMLInputElement) { if (e.currentTarget instanceof HTMLInputElement) {
handleTargetInput(e.currentTarget.value); handleTargetInput(e.currentTarget.value);
} }
@@ -181,8 +200,8 @@
class="flex cursor-pointer 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" class="flex cursor-pointer 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"
role="link" role="link"
tabindex="0" tabindex="0"
on:click={() => goto(resolve(`/report/${report.reportID}`))} onclick={() => goto(resolve(`/report/${report.reportID}`))}
on:keydown={(e) => { onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') { if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault(); e.preventDefault();
goto(resolve(`/report/${report.reportID}`)); goto(resolve(`/report/${report.reportID}`));
@@ -204,7 +223,7 @@
<a <a
href={resolve(`/${report.pasteId}`)} href={resolve(`/${report.pasteId}`)}
class="text-neutral-300 hover:text-white" class="text-neutral-300 hover:text-white"
on:click|stopPropagation onclick={stopPropagation(bubble('click'))}
> >
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId} {report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
</a> </a>
@@ -215,7 +234,7 @@
href={resolve(`/user/${report.targetUsername}`)} href={resolve(`/user/${report.targetUsername}`)}
class="text-neutral-300 hover:text-white" class="text-neutral-300 hover:text-white"
use:tooltip={report.userUUID} use:tooltip={report.userUUID}
on:click|stopPropagation onclick={stopPropagation(bubble('click'))}
> >
{report.targetDisplayName || report.targetUsername} {report.targetDisplayName || report.targetUsername}
</a> </a>
@@ -228,7 +247,7 @@
href={resolve(`/user/${report.reporterUsername}`)} href={resolve(`/user/${report.reporterUsername}`)}
class="text-neutral-300 hover:text-white" class="text-neutral-300 hover:text-white"
use:tooltip={report.reporterUUID} use:tooltip={report.reporterUUID}
on:click|stopPropagation onclick={stopPropagation(bubble('click'))}
> >
{report.reporterDisplayName || report.reporterUsername} {report.reporterDisplayName || report.reporterUsername}
</a> </a>
@@ -251,7 +270,7 @@
<div class="mt-6 flex items-center justify-center gap-4"> <div class="mt-6 flex items-center justify-center gap-4">
<button <button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50" class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => applyFilters(data.reports.pagination.page - 1)} onclick={() => applyFilters(data.reports.pagination.page - 1)}
disabled={data.reports.pagination.page <= 1} disabled={data.reports.pagination.page <= 1}
> >
Prev Prev
@@ -261,7 +280,7 @@
</span> </span>
<button <button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50" class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => applyFilters(data.reports.pagination.page + 1)} onclick={() => applyFilters(data.reports.pagination.page + 1)}
disabled={data.reports.pagination.page >= data.reports.pagination.totalPages} disabled={data.reports.pagination.page >= data.reports.pagination.totalPages}
> >
Next Next
@@ -3,11 +3,17 @@
import { formatBytes, formatNumber, tooltip } from '$lib/utils/misc'; import { formatBytes, formatNumber, tooltip } from '$lib/utils/misc';
import { FileText, Users, Database, TrendingUp } from '@lucide/svelte'; import { FileText, Users, Database, TrendingUp } from '@lucide/svelte';
export let data: PageData; interface Props {
$: stats = data.stats.stats; data: PageData;
}
$: dailyData = stats.pastes.daily || []; let { data }: Props = $props();
$: maxCount = Math.max(...dailyData.map((d: { count: number; date: number }) => d.count), 5); let stats = $derived(data.stats.stats);
let dailyData = $derived(stats.pastes.daily || []);
let maxCount = $derived(
Math.max(...dailyData.map((d: { count: number; date: number }) => d.count), 5)
);
function getOrdinal(n: number) { function getOrdinal(n: number) {
const s = ['th', 'st', 'nd', 'rd']; const s = ['th', 'st', 'nd', 'rd'];
@@ -1,4 +1,7 @@
<script lang="ts"> <script lang="ts">
import { createBubbler, stopPropagation } from 'svelte/legacy';
const bubble = createBubbler();
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { goto, afterNavigate } from '$app/navigation'; import { goto, afterNavigate } from '$app/navigation';
import { page } from '$app/state'; import { page } from '$app/state';
@@ -36,41 +39,46 @@
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report'; import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
import { fade } from 'svelte/transition'; import { fade } from 'svelte/transition';
export let data: PageData; interface Props {
data: PageData;
}
let currentPage = data.pastes?.pagination?.page ?? 1; let { data }: Props = $props();
let pagination: Pagination = data.pastes?.pagination ?? { const initialPagination: Pagination = (() => {
page: 1, const pagination = data.pastes?.pagination;
pageSize: 50, return {
totalCount: 0, page: pagination?.page ?? 1,
totalPages: 1 pageSize: pagination?.pageSize ?? 50,
totalCount: pagination?.totalCount ?? 0,
totalPages: pagination?.totalPages ?? 1
}; };
let pastes = data.pastes?.pastes ?? []; })();
let loading = false;
let isOwner = false; let currentPage = $state(initialPagination.page);
let pagination: Pagination = $state(initialPagination);
let pastes = $state((() => data.pastes?.pastes ?? [])());
let loading = $state(false);
let isOwner = $derived(data.user && $user ? data.user?.uuid === $user.uuid : false);
let modalError = ''; let modalError = '';
let totpEnabled = false; let totpEnabled = $derived(Boolean($user?.totpEnabled));
let now = new Date(); let now = $state(new Date());
let interval: ReturnType<typeof setInterval> | null = null; let interval: ReturnType<typeof setInterval> | null = null;
let isEditingDisplayName = false; let isEditingDisplayName = $state(false);
let editDisplayNameValue = ''; let editDisplayNameValue = $state('');
let apiKeys: { uuid: string; name: string; createdAt: string; lastUsedAt: string | null }[] = []; let apiKeys: { uuid: string; name: string; createdAt: string; lastUsedAt: string | null }[] =
$state([]);
let successfullyFetchedApiKeys = false; let successfullyFetchedApiKeys = false;
let newApiKeyName = ''; let newApiKeyName = $state('');
let newApiKeyValue = ''; let newApiKeyValue = $state('');
let isCreatingApiKey = false; let isCreatingApiKey = $state(false);
let apiKeyError = ''; let apiKeyError = $state('');
let copiedApiKey = false; let copiedApiKey = $state(false);
$: isOwner = data.user && $user ? data.user?.uuid === $user.uuid : false; let reportsSubmitted = $derived(data.reportsSubmitted);
$: totpEnabled = Boolean($user?.totpEnabled); let reportsTarget = $derived(data.reportsTarget);
$: reportsSubmitted = data.reportsSubmitted;
$: reportsTarget = data.reportsTarget;
let activeTab: 'pastes' | 'reportsSubmitted' | 'reportsTarget' | 'settings' = isOwner let activeTab: 'pastes' | 'reportsSubmitted' | 'reportsTarget' | 'settings' = $state('pastes');
? 'settings'
: 'pastes';
async function updateTab(newPageTab: typeof activeTab) { async function updateTab(newPageTab: typeof activeTab) {
if (activeTab === newPageTab) return; if (activeTab === newPageTab) return;
@@ -93,7 +101,7 @@
} }
} }
$: { $effect(() => {
const tab = page.url.searchParams.get('tab'); const tab = page.url.searchParams.get('tab');
switch (tab) { switch (tab) {
case 'pastes': case 'pastes':
@@ -119,7 +127,7 @@
activeTab = 'pastes'; activeTab = 'pastes';
} }
} }
} });
const roleOptions = [ const roleOptions = [
{ label: 'Member', value: 1 }, { label: 'Member', value: 1 },
@@ -245,10 +253,11 @@
} }
function handleTotpConfirm(value: unknown) { function handleTotpConfirm(value: unknown) {
let enabled = totpEnabled;
if (value && typeof value === 'object' && 'enabled' in value) { if (value && typeof value === 'object' && 'enabled' in value) {
totpEnabled = Boolean((value as { enabled?: boolean }).enabled); enabled = Boolean((value as { enabled?: boolean }).enabled);
} }
user.update((u) => (u ? { ...u, totpEnabled } : u)); user.update((u) => (u ? { ...u, totpEnabled: enabled } : u));
modalError = ''; modalError = '';
} }
@@ -425,9 +434,10 @@
} }
}); });
$: reportSiteKey = let reportSiteKey = $derived(
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions (data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
?.cf_turnstile_site_key ?? null; ?.cf_turnstile_site_key ?? null
);
</script> </script>
<svelte:head> <svelte:head>
@@ -525,7 +535,7 @@
<!-- svelte-ignore a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_no_static_element_interactions -->
<div <div
class="absolute top-0 right-0" class="absolute top-0 right-0"
on:click={() => onclick={() =>
openModal({ openModal({
mode: 'report', mode: 'report',
title: 'Report User', title: 'Report User',
@@ -546,7 +556,7 @@
'settings' 'settings'
? 'border-neutral-200 text-white' ? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}" : 'border-transparent text-neutral-400'}"
on:click={() => updateTab('settings')} onclick={() => updateTab('settings')}
> >
Settings Settings
</button> </button>
@@ -556,7 +566,7 @@
'pastes' 'pastes'
? 'border-neutral-200 text-white' ? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}" : 'border-transparent text-neutral-400'}"
on:click={() => updateTab('pastes')} onclick={() => updateTab('pastes')}
> >
Pastes Pastes
<span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300" <span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
@@ -569,7 +579,7 @@
'reportsSubmitted' 'reportsSubmitted'
? 'border-neutral-200 text-white' ? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}" : 'border-transparent text-neutral-400'}"
on:click={() => updateTab('reportsSubmitted')} onclick={() => updateTab('reportsSubmitted')}
> >
Submitted Reports Submitted Reports
<span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300" <span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
@@ -583,7 +593,7 @@
'reportsTarget' 'reportsTarget'
? 'border-neutral-200 text-white' ? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}" : 'border-transparent text-neutral-400'}"
on:click={() => updateTab('reportsTarget')} onclick={() => updateTab('reportsTarget')}
> >
Reports Against User Reports Against User
<span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300" <span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
@@ -624,20 +634,20 @@
bind:value={editDisplayNameValue} bind:value={editDisplayNameValue}
class="w-full border-b border-neutral-600 bg-transparent px-2 py-1 font-mono text-neutral-300 outline-none focus:border-neutral-400" class="w-full border-b border-neutral-600 bg-transparent px-2 py-1 font-mono text-neutral-300 outline-none focus:border-neutral-400"
maxlength="26" maxlength="26"
on:keydown={(e) => { onkeydown={(e) => {
if (e.key === 'Enter') saveDisplayName(); if (e.key === 'Enter') saveDisplayName();
else if (e.key === 'Escape') cancelEditDisplayName(); else if (e.key === 'Escape') cancelEditDisplayName();
}} }}
/> />
<button <button
on:click={saveDisplayName} onclick={saveDisplayName}
class="flex items-center gap-1 rounded bg-green-900/50 px-3 py-2 text-xs font-medium text-green-400 transition-colors hover:bg-green-900" class="flex items-center gap-1 rounded bg-green-900/50 px-3 py-2 text-xs font-medium text-green-400 transition-colors hover:bg-green-900"
> >
<Check class="h-4 w-4" /> <Check class="h-4 w-4" />
Save Save
</button> </button>
<button <button
on:click={cancelEditDisplayName} onclick={cancelEditDisplayName}
class="flex items-center gap-1 rounded bg-neutral-700 px-3 py-2 text-xs font-medium text-neutral-300 transition-colors hover:bg-neutral-600" class="flex items-center gap-1 rounded bg-neutral-700 px-3 py-2 text-xs font-medium text-neutral-300 transition-colors hover:bg-neutral-600"
> >
<X class="h-4 w-4" /> <X class="h-4 w-4" />
@@ -649,7 +659,7 @@
>{data.user?.displayName || data.user?.username}</span >{data.user?.displayName || data.user?.username}</span
> >
<button <button
on:click={startEditDisplayName} onclick={startEditDisplayName}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600" class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
> >
<Pencil class="h-4 w-4" /> <Pencil class="h-4 w-4" />
@@ -683,7 +693,7 @@
> >
</div> </div>
<button <button
on:click={openTotpSetup} onclick={openTotpSetup}
class="rounded bg-neutral-700 px-3 py-1.5 text-xs font-medium transition-colors hover:bg-neutral-600" class="rounded bg-neutral-700 px-3 py-1.5 text-xs font-medium transition-colors hover:bg-neutral-600"
> >
{totpEnabled ? 'Manage' : 'Enable'} {totpEnabled ? 'Manage' : 'Enable'}
@@ -720,7 +730,7 @@
> >
</div> </div>
<button <button
on:click={openEditRoles} onclick={openEditRoles}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600" class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
> >
Edit Edit
@@ -764,7 +774,7 @@
maxlength="26" maxlength="26"
/> />
<button <button
on:click={createApiKey} onclick={createApiKey}
disabled={loading || !newApiKeyName} disabled={loading || !newApiKeyName}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-50" class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-50"
> >
@@ -776,7 +786,7 @@
Create Create
</button> </button>
<button <button
on:click={() => { onclick={() => {
isCreatingApiKey = false; isCreatingApiKey = false;
newApiKeyName = ''; newApiKeyName = '';
}} }}
@@ -787,7 +797,7 @@
</div> </div>
{:else} {:else}
<button <button
on:click={() => (isCreatingApiKey = true)} onclick={() => (isCreatingApiKey = true)}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600" class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
> >
<Plus class="h-4 w-4" /> <Plus class="h-4 w-4" />
@@ -801,7 +811,7 @@
<div class="mb-2 flex items-center justify-between"> <div class="mb-2 flex items-center justify-between">
<span class="text-sm font-medium text-green-400">API Key Created</span> <span class="text-sm font-medium text-green-400">API Key Created</span>
<button <button
on:click={() => (newApiKeyValue = '')} onclick={() => (newApiKeyValue = '')}
class="text-green-400/70 hover:text-green-400" class="text-green-400/70 hover:text-green-400"
> >
<X class="h-4 w-4" /> <X class="h-4 w-4" />
@@ -816,7 +826,7 @@
> >
<button <button
class="p-1 text-neutral-400 hover:text-white" class="p-1 text-neutral-400 hover:text-white"
on:click={() => { onclick={() => {
navigator.clipboard.writeText(newApiKeyValue); navigator.clipboard.writeText(newApiKeyValue);
copiedApiKey = true; copiedApiKey = true;
setTimeout(() => (copiedApiKey = false), 1000); setTimeout(() => (copiedApiKey = false), 1000);
@@ -859,7 +869,7 @@
</div> </div>
</div> </div>
<button <button
on:click={() => deleteApiKey(key.uuid)} onclick={() => deleteApiKey(key.uuid)}
disabled={loading} disabled={loading}
class="p-2 text-neutral-500 transition-colors hover:text-red-400" class="p-2 text-neutral-500 transition-colors hover:text-red-400"
title="Revoke Key" title="Revoke Key"
@@ -894,7 +904,7 @@
</p> </p>
</div> </div>
<button <button
on:click={openDeleteAccount} onclick={openDeleteAccount}
class="rounded border border-red-500/50 bg-red-500/10 px-4 py-2 text-sm font-medium whitespace-nowrap text-red-400 transition-colors hover:bg-red-500 hover:text-white" class="rounded border border-red-500/50 bg-red-500/10 px-4 py-2 text-sm font-medium whitespace-nowrap text-red-400 transition-colors hover:bg-red-500 hover:text-white"
> >
Delete Account Delete Account
@@ -922,7 +932,7 @@
<div class="mt-4 flex items-center justify-center gap-4"> <div class="mt-4 flex items-center justify-center gap-4">
<button <button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50" class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => fetchPage(currentPage - 1)} onclick={() => fetchPage(currentPage - 1)}
disabled={currentPage === 1 || loading} disabled={currentPage === 1 || loading}
> >
Prev Prev
@@ -932,7 +942,7 @@
</span> </span>
<button <button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50" class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => fetchPage(currentPage + 1)} onclick={() => fetchPage(currentPage + 1)}
disabled={currentPage === pagination.totalPages || loading} disabled={currentPage === pagination.totalPages || loading}
> >
Next Next
@@ -946,8 +956,8 @@
class="flex cursor-pointer 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" class="flex cursor-pointer 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"
role="link" role="link"
tabindex="0" tabindex="0"
on:click={() => goto(resolve(`/report/${report.reportID}`))} onclick={() => goto(resolve(`/report/${report.reportID}`))}
on:keydown={(e) => { onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') { if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault(); e.preventDefault();
goto(resolve(`/report/${report.reportID}`)); goto(resolve(`/report/${report.reportID}`));
@@ -969,7 +979,7 @@
<a <a
href={resolve(`/${report.pasteId}`)} href={resolve(`/${report.pasteId}`)}
class="text-neutral-300 hover:text-white" class="text-neutral-300 hover:text-white"
on:click|stopPropagation onclick={stopPropagation(bubble('click'))}
> >
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId} {report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
</a> </a>
@@ -980,7 +990,7 @@
href={resolve(`/user/${report.targetUsername}`)} href={resolve(`/user/${report.targetUsername}`)}
class="text-neutral-300 hover:text-white" class="text-neutral-300 hover:text-white"
use:tooltip={report.userUUID} use:tooltip={report.userUUID}
on:click|stopPropagation onclick={stopPropagation(bubble('click'))}
> >
{report.targetDisplayName || report.targetUsername} {report.targetDisplayName || report.targetUsername}
</a> </a>
@@ -1005,8 +1015,8 @@
class="flex cursor-pointer 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" class="flex cursor-pointer 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"
role="link" role="link"
tabindex="0" tabindex="0"
on:click={() => goto(resolve(`/report/${report.reportID}`))} onclick={() => goto(resolve(`/report/${report.reportID}`))}
on:keydown={(e) => { onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') { if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault(); e.preventDefault();
goto(resolve(`/report/${report.reportID}`)); goto(resolve(`/report/${report.reportID}`));
@@ -1029,7 +1039,7 @@
href={resolve(`/user/${report.reporterUsername}`)} href={resolve(`/user/${report.reporterUsername}`)}
class="text-neutral-300 hover:text-white" class="text-neutral-300 hover:text-white"
use:tooltip={report.reporterUUID} use:tooltip={report.reporterUUID}
on:click|stopPropagation onclick={stopPropagation(bubble('click'))}
> >
{report.reporterDisplayName || report.reporterUsername} {report.reporterDisplayName || report.reporterUsername}
</a> </a>
@@ -1040,7 +1050,7 @@
<a <a
href={resolve(`/${report.pasteId ?? report.pastePID}`)} href={resolve(`/${report.pasteId ?? report.pastePID}`)}
class="text-neutral-300 hover:text-white" class="text-neutral-300 hover:text-white"
on:click|stopPropagation onclick={stopPropagation(bubble('click'))}
> >
{report.pasteTitle ? report.pasteTitle : `Paste #${report.pastePID}`} {report.pasteTitle ? report.pasteTitle : `Paste #${report.pastePID}`}
</a> </a>
@@ -1051,7 +1061,7 @@
href={resolve(`/user/${report.targetUsername}`)} href={resolve(`/user/${report.targetUsername}`)}
class="text-neutral-300 hover:text-white" class="text-neutral-300 hover:text-white"
use:tooltip={report.userUUID} use:tooltip={report.userUUID}
on:click|stopPropagation onclick={stopPropagation(bubble('click'))}
> >
{report.targetDisplayName || report.targetUsername} {report.targetDisplayName || report.targetUsername}
</a> </a>