feat: add markdown parsing and rendering support

fix: resolve lint issues
chore: npm run format

- Added `parseMarkdown` function to handle markdown content with DOMPurify for sanitization.
- Updated `+page.svelte` to render markdown content and handle media loading.
- Introduced new styles for markdown elements in the Svelte component.
- Enhanced media placeholders for external content with privacy warnings.
This commit is contained in:
2026-01-23 01:20:52 -05:00
parent 5e4afafac0
commit 406381fbfe
9 changed files with 879 additions and 32 deletions
@@ -0,0 +1,98 @@
import { marked } from 'marked';
import createDOMPurify from 'dompurify';
import type { WindowLike } from 'dompurify';
const tagMap: Record<string, string> = {
IMG: 'image',
VIDEO: 'video',
AUDIO: 'audio',
IFRAME: 'iframe'
};
export async function parseMarkdown(md: string): Promise<string> {
const html = await marked.parse(md);
let dom: WindowLike & { document: Document };
if (typeof window !== 'undefined') {
dom = window as unknown as WindowLike & { document: Document };
} else {
const { JSDOM } = await import('jsdom');
dom = new JSDOM('').window as unknown as WindowLike & { document: Document };
}
const DOMPurify = createDOMPurify(dom);
DOMPurify.addHook('afterSanitizeElements', (node) => {
if (node.nodeType !== 1) return;
const element = node as Element;
const tag = element.nodeName;
if (tag === 'IMG' || tag === 'VIDEO' || tag === 'IFRAME' || tag === 'AUDIO') {
const src = element.getAttribute('src');
if (!src) return;
let hostname = 'external server';
try {
hostname = new URL(src).hostname;
} catch {
//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);
}
}
});
return DOMPurify.sanitize(html);
}
+3 -3
View File
@@ -1,9 +1,9 @@
<script lang="ts">
import { page } from '$app/state';
$: status = page.status;
$: error = page.error;
$: message = error?.message || 'An unexpected error occurred.';
let status = page.status;
let error = page.error;
let message = error?.message || 'An unexpected error occurred.';
</script>
<svelte:head>
+4 -1
View File
@@ -252,7 +252,10 @@
? estimateEncryptedSize(content + (e.data ?? ''))
: new TextEncoder().encode(content + (e.data ?? '')).length;
if (futureSize > data.options.maxPasteSize && (e.data?.length ?? Number.MAX_SAFE_INTEGER < content.length)) {
if (
futureSize > data.options.maxPasteSize &&
(e.data?.length ?? Number.MAX_SAFE_INTEGER < content.length)
) {
e.preventDefault();
}
}}
+159 -10
View File
@@ -31,6 +31,7 @@
tooltip,
isBinaryData
} from '$lib/utils/misc';
import { parseMarkdown } from '$lib/utils/markdown';
import { syntaxes } from '$lib/consts';
import { resolve } from '$app/paths';
import { decryptAES, encryptAES } from '$lib/utils/encryption';
@@ -124,7 +125,7 @@
return html.replace(code, numbered);
}
function renderCode(content: string | null = null) {
async function renderCode(content: string | null = null) {
if (!data?.paste) return;
let code = content ?? decryptedContent ?? data.content ?? '';
@@ -138,6 +139,14 @@
}
const lang = (data.paste.syntax ?? '').toLowerCase();
if (lang === 'markdown') {
pasteContent = await parseMarkdown(code);
contentRendered = true;
decryptStatus = '';
return;
}
let highlighted = '';
try {
if (lang === 'plaintext') {
@@ -212,7 +221,7 @@
}
data.content = rawContent;
decryptedContent = rawContent;
renderCode(rawContent);
await renderCode(rawContent);
}
if (
(metadata?.syntax !== data.paste.syntax ||
@@ -277,6 +286,76 @@
return value;
}
function handleMarkdownClick(event: MouseEvent) {
const target = event.target as HTMLElement;
const placeholder = target.closest('.media-placeholder') as HTMLElement;
if (placeholder) {
event.preventDefault();
event.stopPropagation();
if (target.classList.contains('load-media-btn')) {
const src = target.getAttribute('data-src');
const tag = target.getAttribute('data-tag');
if (!src || !tag) return;
const element = document.createElement(tag);
if (tag === 'img') {
element.setAttribute('alt', target.getAttribute('data-alt') || '');
element.setAttribute('style', 'max-width:100%; height:auto; border-radius:0.375rem;');
element.onload = () => {
const href = target.getAttribute('data-href');
if (href) {
const anchor = document.createElement('a');
anchor.setAttribute('href', href);
const targetAttr = target.getAttribute('data-target');
if (targetAttr) anchor.setAttribute('target', targetAttr);
anchor.appendChild(element);
placeholder.replaceWith(anchor);
} else {
placeholder.replaceWith(element);
}
};
element.onerror = () => {
target.textContent = 'Error loading image';
target.style.backgroundColor = '#7f1d1d';
target.style.opacity = '1';
};
} else {
if (tag === 'video' || tag === 'audio') {
element.setAttribute('controls', '');
element.setAttribute('style', 'max-width:100%;');
} else if (tag === 'iframe') {
element.setAttribute('style', 'width:100%; min-height:400px; border:none;');
}
const href = target.getAttribute('data-href');
if (href) {
const anchor = document.createElement('a');
anchor.setAttribute('href', href);
const targetAttr = target.getAttribute('data-target');
if (targetAttr) anchor.setAttribute('target', targetAttr);
anchor.appendChild(element);
placeholder.replaceWith(anchor);
} else {
placeholder.replaceWith(element);
}
}
['width', 'height', 'title'].forEach((attr) => {
const val = target.getAttribute(`data-${attr}`);
if (val) element.setAttribute(attr, val);
});
target.textContent = 'Loading...';
target.style.opacity = '0.5';
target.style.cursor = 'wait';
element.setAttribute('src', src);
}
}
}
onMount(async () => {
try {
if (data?.paste && data.paste.visibility === 2) {
@@ -297,14 +376,14 @@
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
} else {
renderCode();
await renderCode();
history.replaceState(null, '', window.location.pathname + window.location.search);
}
} else {
decryptStatus = 'Decryption canceled.';
}
} else {
renderCode();
await renderCode();
}
return;
}
@@ -317,18 +396,18 @@
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
} else {
renderCode();
await renderCode();
}
} else {
decryptStatus = 'Decryption canceled.';
}
} else {
decryptStatus = 'Rendering content...';
renderCode();
await renderCode();
}
} catch {
decryptStatus = 'Rendering content...';
renderCode();
await renderCode();
}
});
@@ -776,13 +855,17 @@
>
<span class="monospace">{decryptStatus || 'Loading...'}</span>
</div>
<code
class="codeblock-with-lines overflow-x-auto overflow-y-auto"
<div
class={data.paste.syntax === 'markdown'
? 'markdown rounded-b-md bg-neutral-800 p-4'
: 'codeblock-with-lines overflow-x-auto overflow-y-auto'}
class:hidden={!contentRendered}
on:click={handleMarkdownClick}
role="presentation"
>
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html pasteContent}
</code>
</div>
{/if}
{:else}
<h1 class="mb-4 text-center text-4xl font-bold">Paste not found</h1>
@@ -794,6 +877,72 @@
.hljs {
background-color: var(--color-neutral-800) !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;
}
.codeblock-with-lines {
display: block;
width: 100%;
@@ -83,7 +83,10 @@
<svelte:head>
<title>Login - Sharpbin</title>
<meta name="description" content="Login to your Sharpbin account to manage your pastes and settings." />
<meta
name="description"
content="Login to your Sharpbin account to manage your pastes and settings."
/>
</svelte:head>
<main
@@ -4,17 +4,16 @@ import { extractError } from '$lib/utils/misc';
import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ fetch }) => {
try {
const res = await fetch('/api/paste/recent');
if (!res.ok) {
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
throw error(res.status, errorMsg);
}
const recentPastes: Paste[] = await res.json();
return { recentPastes };
}
catch (error) {
console.error(error);
return { recentPastes: [] };
}
try {
const res = await fetch('/api/paste/recent');
if (!res.ok) {
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
throw error(res.status, errorMsg);
}
const recentPastes: Paste[] = await res.json();
return { recentPastes };
} catch (error) {
console.error(error);
return { recentPastes: [] };
}
};
@@ -14,7 +14,7 @@
export let data: PageData;
$: now = new Date();
let now = new Date();
onMount(() => {
const interval = setInterval(() => {
@@ -39,7 +39,7 @@
{:else}
<h1 class="mb-4 text-3xl font-bold">Recent Pastes</h1>
<div class="grid grid-cols-1 gap-4">
{#each data.recentPastes as paste}
{#each data.recentPastes as paste (paste.uuid)}
{@const createdAt = extractDateFromUUIDv7(paste.uuid)}
{@const syntax = syntaxes[paste.syntax] ?? syntaxes['plaintext']}
@@ -48,7 +48,7 @@
class="flex flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
>
<span
class="w-fit truncate text-lg max-w-full font-semibold text-neutral-100 hover:text-white"
class="w-fit max-w-full truncate text-lg font-semibold text-neutral-100 hover:text-white"
use:tooltip={paste.title || 'Untitled Paste'}
>
{paste.title || 'Untitled Paste'}