feat: preview markdown in paste creation; prevent external option in parseMarkdown

This commit is contained in:
2026-01-23 02:06:54 -05:00
parent 825d384db4
commit 3f27a3a3e7
4 changed files with 297 additions and 236 deletions
+71 -69
View File
@@ -9,7 +9,7 @@ const tagMap: Record<string, string> = {
IFRAME: 'iframe' IFRAME: 'iframe'
}; };
export async function parseMarkdown(md: string): Promise<string> { export async function parseMarkdown(md: string, preventExternal: boolean = true): Promise<string> {
const html = await marked.parse(md); const html = await marked.parse(md);
let dom: WindowLike & { document: Document }; let dom: WindowLike & { document: Document };
@@ -24,77 +24,79 @@ export async function parseMarkdown(md: string): Promise<string> {
const DOMPurify = createDOMPurify(dom); const DOMPurify = createDOMPurify(dom);
DOMPurify.addHook('afterSanitizeElements', (node) => { if (preventExternal) {
if (node.nodeType !== 1) return; DOMPurify.addHook('afterSanitizeElements', (node) => {
const element = node as Element; if (node.nodeType !== 1) return;
const element = node as Element;
const tag = element.nodeName; const tag = element.nodeName;
if (tag === 'IMG' || tag === 'VIDEO' || tag === 'IFRAME' || tag === 'AUDIO') { if (tag === 'IMG' || tag === 'VIDEO' || tag === 'IFRAME' || tag === 'AUDIO') {
const src = element.getAttribute('src'); const src = element.getAttribute('src');
if (!src) return; if (!src) return;
let hostname = 'external server'; let hostname = 'external server';
try { try {
hostname = new URL(src).hostname; hostname = new URL(src).hostname;
} catch { } catch {
//might be a relative url //might be a relative url
}
const placeholder = dom.document.createElement('span');
placeholder.className = 'media-placeholder';
placeholder.setAttribute(
'style',
'border: 1px solid #404040; padding: 1rem; margin: 1rem 0; border-radius: 0.5rem; background-color: #1e1e1e; text-align: center; display: block; font-style: normal; color: white; cursor: default; text-decoration: none; user-select: none;'
);
const warning = dom.document.createElement('span');
warning.textContent = `External ${tagMap[tag] || tag.toLowerCase()} hidden for privacy.`;
warning.setAttribute(
'style',
'margin-bottom: 0.5rem; font-weight: bold; display: block; text-decoration: none;'
);
const subWarning = dom.document.createElement('span');
subWarning.textContent = `Loading this will expose your IP address to ${hostname}.`;
subWarning.setAttribute(
'style',
'font-size: 0.75rem; color: #a3a3a3; margin-bottom: 1rem; display: block; text-decoration: none;'
);
const button = dom.document.createElement('button');
button.textContent = `Load ${tagMap[tag] || tag.toLowerCase()}`;
button.className = 'load-media-btn';
button.setAttribute('data-src', src);
button.setAttribute('data-tag', tag.toLowerCase());
button.setAttribute(
'style',
'background-color: #404040; color: white; padding: 0.25rem 0.75rem; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
);
if (element.getAttribute('alt'))
button.setAttribute('data-alt', element.getAttribute('alt') || '');
if (element.getAttribute('title'))
button.setAttribute('data-title', element.getAttribute('title') || '');
if (element.getAttribute('width'))
button.setAttribute('data-width', element.getAttribute('width') || '');
if (element.getAttribute('height'))
button.setAttribute('data-height', element.getAttribute('height') || '');
placeholder.appendChild(warning);
placeholder.appendChild(subWarning);
placeholder.appendChild(button);
const parent = element.parentNode;
if (parent && parent.nodeName === 'A') {
const anchor = parent as HTMLElement;
button.setAttribute('data-href', anchor.getAttribute('href') || '');
button.setAttribute('data-target', anchor.getAttribute('target') || '');
anchor.parentNode?.replaceChild(placeholder, anchor);
} else {
element.parentNode?.replaceChild(placeholder, element);
}
} }
});
const placeholder = dom.document.createElement('span'); }
placeholder.className = 'media-placeholder';
placeholder.setAttribute(
'style',
'border: 1px solid #404040; padding: 1rem; margin: 1rem 0; border-radius: 0.5rem; background-color: #1e1e1e; text-align: center; display: block; font-style: normal; color: white; cursor: default; text-decoration: none; user-select: none;'
);
const warning = dom.document.createElement('span');
warning.textContent = `External ${tagMap[tag] || tag.toLowerCase()} hidden for privacy.`;
warning.setAttribute(
'style',
'margin-bottom: 0.5rem; font-weight: bold; display: block; text-decoration: none;'
);
const subWarning = dom.document.createElement('span');
subWarning.textContent = `Loading this will expose your IP address to ${hostname}.`;
subWarning.setAttribute(
'style',
'font-size: 0.75rem; color: #a3a3a3; margin-bottom: 1rem; display: block; text-decoration: none;'
);
const button = dom.document.createElement('button');
button.textContent = `Load ${tagMap[tag] || tag.toLowerCase()}`;
button.className = 'load-media-btn';
button.setAttribute('data-src', src);
button.setAttribute('data-tag', tag.toLowerCase());
button.setAttribute(
'style',
'background-color: #404040; color: white; padding: 0.25rem 0.75rem; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
);
if (element.getAttribute('alt'))
button.setAttribute('data-alt', element.getAttribute('alt') || '');
if (element.getAttribute('title'))
button.setAttribute('data-title', element.getAttribute('title') || '');
if (element.getAttribute('width'))
button.setAttribute('data-width', element.getAttribute('width') || '');
if (element.getAttribute('height'))
button.setAttribute('data-height', element.getAttribute('height') || '');
placeholder.appendChild(warning);
placeholder.appendChild(subWarning);
placeholder.appendChild(button);
const parent = element.parentNode;
if (parent && parent.nodeName === 'A') {
const anchor = parent as HTMLElement;
button.setAttribute('data-href', anchor.getAttribute('href') || '');
button.setAttribute('data-target', anchor.getAttribute('target') || '');
anchor.parentNode?.replaceChild(placeholder, anchor);
} else {
element.parentNode?.replaceChild(placeholder, element);
}
}
});
return DOMPurify.sanitize(html); return DOMPurify.sanitize(html);
} }
+141 -83
View File
@@ -13,6 +13,7 @@
tooltip, tooltip,
syntaxFromExtension syntaxFromExtension
} from '$lib/utils/misc'; } from '$lib/utils/misc';
import { parseMarkdown } from '$lib/utils/markdown';
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, Eye, EyeClosed, Dices } from '@lucide/svelte'; import { FileUp, X, Eye, EyeClosed, Dices } from '@lucide/svelte';
@@ -32,14 +33,32 @@
let anonymousUpload = false; let anonymousUpload = false;
let isDragging = false; let isDragging = false;
let dragError = ''; let dragError = '';
let previewMode = false;
let renderedMarkdown = '';
$: currentByteSize = $: currentByteSize =
selectedVisibility === 2 selectedVisibility === 2
? estimateEncryptedSize(content) ? estimateEncryptedSize(content)
: new TextEncoder().encode(content).length; : new TextEncoder().encode(content).length;
$: if (selectedSyntax !== 'markdown') {
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';
async function togglePreview(toPreview: boolean) {
if (toPreview && !previewMode) {
previewHeight = textArea?.style.height || 'auto';
renderedMarkdown = await parseMarkdown(content, false);
}
previewMode = toPreview;
if (!toPreview) {
requestAnimationFrame(resize);
}
}
function resize() { function resize() {
if (!textArea) return; if (!textArea) return;
@@ -233,78 +252,88 @@
/> />
<div> <div>
<div class="relative"> <div class="relative">
<textarea {#if previewMode}
placeholder="Your paste content here..." <div
class="min-h-20 w-full resize-none overflow-hidden rounded rounded-b-none border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200" class="markdown min-h-20 w-full overflow-y-auto rounded rounded-b-none border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200"
spellcheck="false" style="height: {previewHeight}"
autocomplete="off" >
minlength="1" {@html renderedMarkdown}
bind:this={textArea} </div>
bind:value={content} {:else}
on:input={resize} <textarea
on:change={resize} placeholder="Your paste content here..."
on:focus={resize} class="min-h-20 w-full resize-none overflow-hidden rounded rounded-b-none border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200"
on:beforeinput={(e) => { spellcheck="false"
if (!data.options?.maxPasteSize) return; autocomplete="off"
minlength="1"
bind:this={textArea}
bind:value={content}
on:input={resize}
on:change={resize}
on:focus={resize}
on:beforeinput={(e) => {
if (!data.options?.maxPasteSize) return;
const futureSize = const futureSize =
selectedVisibility === 2 selectedVisibility === 2
? estimateEncryptedSize(content + (e.data ?? '')) ? estimateEncryptedSize(content + (e.data ?? ''))
: new TextEncoder().encode(content + (e.data ?? '')).length; : new TextEncoder().encode(content + (e.data ?? '')).length;
if ( if (
futureSize > data.options.maxPasteSize && futureSize > data.options.maxPasteSize &&
(e.data?.length ?? Number.MAX_SAFE_INTEGER < content.length) (e.data?.length ?? Number.MAX_SAFE_INTEGER < content.length)
) { ) {
e.preventDefault();
}
}}
on:dragenter={(e) => {
e.preventDefault(); e.preventDefault();
} isDragging = true;
}} }}
on:dragenter={(e) => { on:dragover={(e) => {
e.preventDefault(); e.preventDefault();
isDragging = true; isDragging = true;
}} }}
on:dragover={(e) => { on:dragleave={(e) => {
e.preventDefault(); e.preventDefault();
isDragging = true; isDragging = false;
}} }}
on:dragleave={(e) => { on:drop={(e) => {
e.preventDefault(); requestAnimationFrame(resize);
isDragging = false; e.preventDefault();
}} isDragging = false;
on:drop={(e) => {
requestAnimationFrame(resize);
e.preventDefault();
isDragging = false;
const file = e.dataTransfer?.files[0]; const file = e.dataTransfer?.files[0];
if (!file) return; if (!file) return;
const reader = new FileReader(); const reader = new FileReader();
reader.onload = (e) => { reader.onload = (e) => {
const arrayBuffer = e.target?.result as ArrayBuffer; const arrayBuffer = e.target?.result as ArrayBuffer;
if (isBinaryData(new Uint8Array(arrayBuffer))) { if (isBinaryData(new Uint8Array(arrayBuffer))) {
content = ''; content = '';
dragError = 'The dropped file appears to be binary and cannot be pasted as text.'; dragError =
setTimeout(() => { 'The dropped file appears to be binary and cannot be pasted as text.';
dragError = ''; setTimeout(() => {
}, 5000); dragError = '';
return; }, 5000);
} return;
const syntax = syntaxFromExtension(file.name.split('.').pop() || ''); }
if (syntax && selectedSyntax !== syntax) { const syntax = syntaxFromExtension(file.name.split('.').pop() || '');
selectedSyntax = syntax; if (syntax && selectedSyntax !== syntax) {
} else if (!syntax && selectedSyntax !== 'plaintext') { selectedSyntax = syntax;
selectedSyntax = 'plaintext'; } else if (!syntax && selectedSyntax !== 'plaintext') {
} selectedSyntax = 'plaintext';
title = file.name; }
const decoder = new TextDecoder(); title = file.name;
content = decoder.decode(arrayBuffer); const decoder = new TextDecoder();
}; content = decoder.decode(arrayBuffer);
};
reader.readAsArrayBuffer(file); reader.readAsArrayBuffer(file);
}} }}
></textarea> ></textarea>
{/if}
{#if isDragging || (dragError && dragError !== '')} {#if isDragging || (dragError && dragError !== '')}
<div <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" 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"
@@ -331,25 +360,54 @@
</div> </div>
{/if} {/if}
</div> </div>
<div <div class="mt-1 flex">
class="monospace mb-2 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" {#if selectedSyntax === 'markdown'}
> <div
<div class="flex flex-col md:flex-row md:gap-2"> class="monospace mb-2 flex h-12 w-36 items-center justify-between gap-1 rounded-bl border border-neutral-700 bg-neutral-800 p-1 text-sm text-neutral-400 md:h-8"
<span>
{content.split('\n').length} line{content.split('\n').length !== 1 ? 's' : ''}
</span>
<span class="hidden text-neutral-600 md:block">•</span>
<span>{formatNumber(content.length)} char{content.length !== 1 ? 's' : ''}</span>
</div>
<div class="flex flex-col text-center md:flex-row md:gap-2">
<span
class="border-b border-neutral-600 md:border-0"
class:text-red-500={currentByteSize > (data.options?.maxPasteSize ?? 0)}
> >
{formatBytes(currentByteSize)} <button
</span> type="button"
<span class="hidden md:block">/</span> class="h-full w-1/2 rounded-l transition-colors {previewMode
{formatBytes(data.options?.maxPasteSize ?? 0)} ? 'hover:bg-neutral-700'
: 'bg-neutral-700 text-white'}"
on:click={() => togglePreview(false)}
>
Code
</button>
<button
type="button"
class="h-full w-1/2 rounded-r transition-colors {!previewMode
? 'hover:bg-neutral-700'
: 'bg-neutral-700 text-white'}"
on:click={() => togglePreview(true)}
>
Preview
</button>
</div>
{/if}
<div
class="monospace mb-2 flex h-12 items-center justify-between {selectedSyntax ===
'markdown'
? 'ml-auto w-[calc(100%-150px)] rounded-br'
: 'w-full rounded-b'} border border-neutral-700 bg-neutral-800 p-1 pr-2 pl-2 text-sm text-neutral-400 md:h-8"
>
<div class="flex flex-col md:flex-row md:gap-2">
<span>
{content.split('\n').length} line{content.split('\n').length !== 1 ? 's' : ''}
</span>
<span class="hidden text-neutral-600 md:block">•</span>
<span>{formatNumber(content.length)} char{content.length !== 1 ? 's' : ''}</span>
</div>
<div class="flex flex-col text-center md:flex-row md:gap-2">
<span
class="border-b border-neutral-600 md:border-0"
class:text-red-500={currentByteSize > (data.options?.maxPasteSize ?? 0)}
>
{formatBytes(currentByteSize)}
</span>
<span class="hidden md:block">/</span>
{formatBytes(data.options?.maxPasteSize ?? 0)}
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -877,90 +877,6 @@
.hljs { .hljs {
background-color: var(--color-neutral-800) !important; background-color: var(--color-neutral-800) !important;
} }
.markdown > :first-child {
margin-top: 0 !important;
padding-top: 0 !important;
}
.markdown h1 {
font-size: 2.25rem;
font-weight: 700;
margin-top: 1.5rem;
margin-bottom: 1rem;
border-bottom: 1px solid var(--color-neutral-700);
padding-bottom: 0.3rem;
}
.markdown h2 {
font-size: 1.875rem;
font-weight: 600;
margin-top: 1.25rem;
margin-bottom: 0.75rem;
border-bottom: 1px solid var(--color-neutral-700);
padding-bottom: 0.2rem;
}
.markdown h3 {
font-size: 1.5rem;
font-weight: 600;
margin-top: 1rem;
margin-bottom: 0.5rem;
}
.markdown p {
margin-bottom: 1rem;
line-height: 1.6;
}
.markdown ul {
list-style-type: disc;
margin-left: 1.5rem;
margin-bottom: 1rem;
}
.markdown ol {
list-style-type: decimal;
margin-left: 1.5rem;
margin-bottom: 1rem;
}
.markdown li {
margin-bottom: 0.25rem;
}
.markdown a {
color: #3b82f6;
text-decoration: underline;
}
.markdown .load-media-btn:hover {
background-color: #525252 !important;
}
.markdown pre {
background-color: #1a1a1a;
padding: 1rem;
border-radius: 0.375rem;
margin-bottom: 1rem;
overflow-x: auto;
}
.markdown code {
background-color: #1a1a1a;
padding: 0.2rem 0.4rem;
border-radius: 0.25rem;
font-family: monospace;
}
.markdown blockquote {
border-left: 4px solid #404040;
padding-left: 1rem;
color: #a3a3a3;
font-style: italic;
margin-bottom: 1rem;
}
.markdown table {
width: 100%;
border-collapse: collapse;
margin-bottom: 1rem;
}
.markdown th,
.markdown td {
border: 1px solid #404040;
padding: 0.5rem;
text-align: left;
}
.markdown th {
background-color: #2a2a2a;
}
.codeblock-with-lines { .codeblock-with-lines {
display: block; display: block;
+85
View File
@@ -34,3 +34,88 @@ textarea,
select { select {
outline: none; outline: none;
} }
.markdown > :first-child {
margin-top: 0 !important;
padding-top: 0 !important;
}
.markdown h1 {
font-size: 2.25rem;
font-weight: 700;
margin-top: 1.5rem;
margin-bottom: 1rem;
border-bottom: 1px solid var(--color-neutral-700);
padding-bottom: 0.3rem;
}
.markdown h2 {
font-size: 1.875rem;
font-weight: 600;
margin-top: 1.25rem;
margin-bottom: 0.75rem;
border-bottom: 1px solid var(--color-neutral-700);
padding-bottom: 0.2rem;
}
.markdown h3 {
font-size: 1.5rem;
font-weight: 600;
margin-top: 1rem;
margin-bottom: 0.5rem;
}
.markdown p {
margin-bottom: 1rem;
line-height: 1.6;
}
.markdown ul {
list-style-type: disc;
margin-left: 1.5rem;
margin-bottom: 1rem;
}
.markdown ol {
list-style-type: decimal;
margin-left: 1.5rem;
margin-bottom: 1rem;
}
.markdown li {
margin-bottom: 0.25rem;
}
.markdown a {
color: #3b82f6;
text-decoration: underline;
}
.markdown .load-media-btn:hover {
background-color: #525252 !important;
}
.markdown pre {
background-color: #1a1a1a;
padding: 1rem;
border-radius: 0.375rem;
margin-bottom: 1rem;
overflow-x: auto;
}
.markdown code {
background-color: #1a1a1a;
padding: 0.2rem 0.4rem;
border-radius: 0.25rem;
font-family: monospace;
}
.markdown blockquote {
border-left: 4px solid #404040;
padding-left: 1rem;
color: #a3a3a3;
font-style: italic;
margin-bottom: 1rem;
}
.markdown table {
width: 100%;
border-collapse: collapse;
margin-bottom: 1rem;
}
.markdown th,
.markdown td {
border: 1px solid #404040;
padding: 0.5rem;
text-align: left;
}
.markdown th {
background-color: #2a2a2a;
}