feat: add isBinaryData utility function and integrate it into paste handling; add drag and drop functionality when creating a paste

This commit is contained in:
2026-01-19 03:37:28 -05:00
parent 1ed21789e6
commit bf0eac9ed8
3 changed files with 192 additions and 80 deletions
+13
View File
@@ -24,6 +24,19 @@ export function extractDateFromUUIDv7(uuid?: string): Date | null {
return new Date(parseInt(timestampHex, 16)); return new Date(parseInt(timestampHex, 16));
} }
export function isBinaryData(buffer: ArrayBuffer | Uint8Array): boolean {
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
if (bytes.includes(0)) return true;
try {
new TextDecoder('utf-8', { fatal: true }).decode(bytes);
return false;
} catch {
return true;
}
}
export function extractError(resData: unknown): string | null { export function extractError(resData: unknown): string | null {
if (!resData || typeof resData !== 'object') return null; if (!resData || typeof resData !== 'object') return null;
+89 -20
View File
@@ -4,11 +4,12 @@
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import { getToken } from '$lib/utils/auth'; import { getToken } from '$lib/utils/auth';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { fly } from 'svelte/transition'; import { fly, fade } from 'svelte/transition';
import { encryptAES } from '$lib/utils/encryption'; import { encryptAES } from '$lib/utils/encryption';
import { formatBytes, formatNumber } from '$lib/utils/misc'; import { formatBytes, formatNumber, isBinaryData } from '$lib/utils/misc';
import Dropdown from '$lib/components/Dropdown.svelte'; import Dropdown from '$lib/components/Dropdown.svelte';
import { SvelteURLSearchParams } from 'svelte/reactivity'; import { SvelteURLSearchParams } from 'svelte/reactivity';
import { FileUp, X } from '@lucide/svelte';
export let data: PageData; export let data: PageData;
@@ -20,6 +21,8 @@
let selectedVisibility = data.options?.visibilities?.[0]?.value; let selectedVisibility = data.options?.visibilities?.[0]?.value;
let password = ''; let password = '';
let anonymousUpload = false; let anonymousUpload = false;
let isDragging = false;
let dragError = '';
onMount(() => { onMount(() => {
const render = () => { const render = () => {
@@ -98,12 +101,14 @@
if (selectedVisibility === 2) { if (selectedVisibility === 2) {
body = await encryptAES(content, password); body = await encryptAES(content, password);
} }
const url = `/api/paste/create?${params.toString()}`; const url = `/api/paste/create?${params.toString()}`;
const options: RequestInit = { const options: RequestInit = {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'text/plain' }, headers: { 'Content-Type': 'text/plain' },
body body
}; };
if ($user && !anonymousUpload) { if ($user && !anonymousUpload) {
const token = getToken(); const token = getToken();
if (token) { if (token) {
@@ -142,7 +147,7 @@
error = resData.message || 'Registration failed. Please try again.'; error = resData.message || 'Registration failed. Please try again.';
} }
} }
setInterval(() => { setTimeout(() => {
error = ''; error = '';
}, 5000); }, 5000);
} }
@@ -173,24 +178,88 @@
bind:value={title} bind:value={title}
maxlength={data.options?.maxTitleLength ?? 500} maxlength={data.options?.maxTitleLength ?? 500}
/> />
<div class="relative"> <div>
<textarea <div class="relative">
placeholder="Your paste content here..." <textarea
class=" h-64 max-h-[50vh] min-h-10 w-full resize-y rounded rounded-b-none border border-neutral-700 bg-neutral-800 p-2" placeholder="Your paste content here..."
spellcheck="false" class="h-64 max-h-[50vh] min-h-20 w-full resize-y rounded rounded-b-none border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200"
autocomplete="off" spellcheck="false"
bind:value={content} autocomplete="off"
on:beforeinput={(e) => { bind:value={content}
if ( on:beforeinput={(e) => {
data.options?.maxPasteSize && if (
(new TextEncoder().encode(content).length >= data.options.maxPasteSize || data.options?.maxPasteSize &&
(e.data && (new TextEncoder().encode(content).length >= data.options.maxPasteSize ||
new TextEncoder().encode(content + e.data).length > data.options.maxPasteSize)) (e.data &&
) { new TextEncoder().encode(content + e.data).length > data.options.maxPasteSize))
) {
e.preventDefault();
}
}}
on:dragenter={(e) => {
e.preventDefault(); e.preventDefault();
} isDragging = true;
}} }}
></textarea> on:dragover={(e) => {
e.preventDefault();
isDragging = true;
}}
on:dragleave={(e) => {
e.preventDefault();
isDragging = false;
}}
on:drop={(e) => {
e.preventDefault();
isDragging = false;
const file = e.dataTransfer?.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const arrayBuffer = e.target?.result as ArrayBuffer;
if (isBinaryData(new Uint8Array(arrayBuffer))) {
content = '';
dragError = 'The dropped file appears to be binary and cannot be pasted as text.';
setTimeout(() => {
dragError = '';
}, 5000);
return;
}
const decoder = new TextDecoder();
content = decoder.decode(arrayBuffer);
};
reader.readAsArrayBuffer(file);
}}
></textarea>
{#if isDragging || (dragError && dragError !== '')}
<div
class="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-md rounded-b-none border-2 border-dashed border-neutral-500 bg-neutral-800/70 text-center text-neutral-300"
transition:fade={{ duration: 150 }}
>
<div class="relative flex h-full w-full items-center justify-center">
{#if dragError && dragError !== ''}
<div
class="absolute flex flex-col items-center gap-4"
transition:fly={{ y: -20, duration: 200 }}
>
<X class="h-12 w-12 text-red-500" />
<p>{dragError}</p>
</div>
{:else}
<div
class="absolute flex flex-col items-center gap-4"
transition:fly={{ y: -20, duration: 200 }}
>
<FileUp class="h-12 w-12" />
</div>
{/if}
</div>
</div>
{/if}
</div>
<div <div
class="monospace mb-4 flex h-12 items-center justify-between rounded-b border border-neutral-700 bg-neutral-800 p-1 pr-2 pl-2 text-sm text-neutral-400 md:h-8" class="monospace mb-4 flex h-12 items-center justify-between rounded-b border border-neutral-700 bg-neutral-800 p-1 pr-2 pl-2 text-sm text-neutral-400 md:h-8"
> >
+90 -60
View File
@@ -28,7 +28,8 @@
formatNumber, formatNumber,
extractDateFromUUIDv7, extractDateFromUUIDv7,
dateToRelativeString, dateToRelativeString,
tooltip tooltip,
isBinaryData
} from '$lib/utils/misc'; } from '$lib/utils/misc';
import { displayNames } from '$lib/consts'; import { displayNames } from '$lib/consts';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
@@ -47,6 +48,7 @@
let editMetadata: Paste | null = data.paste ? { ...data.paste } : null; let editMetadata: Paste | null = data.paste ? { ...data.paste } : null;
let editError = ''; let editError = '';
let editLoading = false; let editLoading = false;
let isBinary = false;
let pasteContent = ''; let pasteContent = '';
let decryptedContent: string | null = null; let decryptedContent: string | null = null;
let decryptError = ''; let decryptError = '';
@@ -124,6 +126,15 @@
function renderCode(content: string | null = null) { function renderCode(content: string | null = null) {
if (!data?.paste) return; if (!data?.paste) return;
let code = content ?? decryptedContent ?? data.content ?? ''; let code = content ?? decryptedContent ?? data.content ?? '';
const encoder = new TextEncoder();
const buffer = encoder.encode(code).buffer;
isBinary = isBinaryData(buffer);
if (isBinary) {
contentRendered = true;
return;
}
const lang = (data.paste.syntax ?? '').toLowerCase(); const lang = (data.paste.syntax ?? '').toLowerCase();
let highlighted = ''; let highlighted = '';
try { try {
@@ -385,7 +396,12 @@
<div class="mb-2"> <div class="mb-2">
<div class="flex flex-wrap items-center justify-center gap-4"> <div class="flex flex-wrap items-center justify-center gap-4">
<div class="relative flex shrink-0 items-center"> <div class="relative flex shrink-0 items-center">
<div class="flex" use:tooltip={data.paste.isCompressed ? `Compressed Size: ${formatBytes(data.paste.size)}` : `This paste is not compressed.`}> <div
class="flex"
use:tooltip={data.paste.isCompressed
? `Compressed Size: ${formatBytes(data.paste.size)}`
: `This paste is not compressed.`}
>
<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.trueSize)}</span> <span class="text-neutral-400">{formatBytes(data.paste.trueSize)}</span>
</div> </div>
@@ -509,53 +525,59 @@
<div <div
class="sticky top-0 z-10 flex flex-col items-center justify-between gap-2 rounded-t-md border-b border-neutral-700 bg-neutral-800 px-3 py-2 md:flex-row" class="sticky top-0 z-10 flex flex-col items-center justify-between gap-2 rounded-t-md border-b border-neutral-700 bg-neutral-800 px-3 py-2 md:flex-row"
> >
<div class="flex items-center gap-2 text-sm text-neutral-300"> {#if !isBinary}
<span class="font-medium text-neutral-100" <div class="flex items-center gap-2 text-sm text-neutral-300">
>{formatNumber((editContent ?? decryptedContent ?? data.content).length)}</span <span class="font-medium text-neutral-100"
> >{formatNumber((editContent ?? decryptedContent ?? data.content).length)}</span
<span class="text-neutral-400">chars</span> >
<span class="text-neutral-600">•</span> <span class="text-neutral-400">chars</span>
<span class="font-medium text-neutral-100" <span class="text-neutral-600">•</span>
>{formatNumber( <span class="font-medium text-neutral-100"
(editing ? (editContent ?? '') : (decryptedContent ?? data.content)).split('\n') >{formatNumber(
.length (editing ? (editContent ?? '') : (decryptedContent ?? data.content)).split('\n')
)}</span .length
> )}</span
<span class="text-neutral-400" >
>line{(editing ? (editContent ?? '') : (decryptedContent ?? data.content)).split('\n') <span class="text-neutral-400"
.length !== 1 >line{(editing ? (editContent ?? '') : (decryptedContent ?? data.content)).split('\n')
? 's' .length !== 1
: ''}</span ? 's'
> : ''}</span
</div> >
</div>
{:else}
<div></div>
{/if}
<div class="flex shrink-0 flex-wrap items-center gap-2 sm:flex-nowrap"> <div class="flex shrink-0 flex-wrap items-center gap-2 sm:flex-nowrap">
<button {#if !isBinary}
type="button" <button
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600" type="button"
on:click={() => { class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
navigator.clipboard.writeText(decryptedContent ?? data.content); on:click={() => {
copiedPaste = true; navigator.clipboard.writeText(decryptedContent ?? data.content);
setTimeout(() => (copiedPaste = false), 1000); copiedPaste = true;
}} setTimeout(() => (copiedPaste = false), 1000);
> }}
<div class="relative mr-1 h-5 w-5"> >
{#if copiedPaste} <div class="relative mr-1 h-5 w-5">
<span {#if copiedPaste}
transition:fade={{ duration: 200 }} <span
class="absolute inset-0 flex items-center justify-center" transition:fade={{ duration: 200 }}
><Check class="h-5 w-5 text-green-400" /></span class="absolute inset-0 flex items-center justify-center"
> ><Check class="h-5 w-5 text-green-400" /></span
{:else} >
<span {:else}
transition:fade={{ duration: 200 }} <span
class="absolute inset-0 flex items-center justify-center" transition:fade={{ duration: 200 }}
><Copy class="h-5 w-5 text-neutral-400" /></span class="absolute inset-0 flex items-center justify-center"
> ><Copy class="h-5 w-5 text-neutral-400" /></span
{/if} >
</div> {/if}
</div>
<span class="text-neutral-300">Copy</span> <span class="text-neutral-300">Copy</span>
</button> </button>
{/if}
<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"
@@ -618,18 +640,20 @@
{/if} {/if}
{#if $user && ($user.uuid === data.paste?.author?.uuid || $user.roles.some((r) => r === 1 || r === 255))} {#if $user && ($user.uuid === data.paste?.author?.uuid || $user.roles.some((r) => r === 1 || r === 255))}
{#if !editing} {#if !editing}
<button {#if !isBinary}
type="button" <button
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600" type="button"
on:click={() => { class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
editContent = decryptedContent ?? data.content; on:click={() => {
editError = ''; editContent = decryptedContent ?? data.content;
editing = true; editError = '';
}} editing = true;
> }}
<Pencil class="mr-1 h-5 w-5 text-neutral-400" /> >
<span class="text-neutral-300">Edit</span> <Pencil class="mr-1 h-5 w-5 text-neutral-400" />
</button> <span class="text-neutral-300">Edit</span>
</button>
{/if}
<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"
@@ -698,7 +722,13 @@
{/if} {/if}
</div> </div>
</div> </div>
{#if editing} {#if isBinary}
<div
class="flex h-16 w-full flex-col items-center justify-center rounded-b bg-neutral-800 p-4 text-neutral-400"
>
<p>We cannot display this paste because it is not text</p>
</div>
{:else if editing}
<textarea <textarea
class="mb-3 max-h-[40vh] min-h-10 w-full rounded-b bg-neutral-800 p-2 font-mono" class="mb-3 max-h-[40vh] min-h-10 w-full rounded-b bg-neutral-800 p-2 font-mono"
rows="14" rows="14"