This repository has been archived on 2026-09-04. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
KSnippets/snippets-frontend/app/page.tsx
T
2026-08-27 21:05:25 +08:00

148 lines
7.3 KiB
TypeScript

'use client'
import {FormEvent, useState} from 'react'
import {ArrowUpRight, Check, Copy, FileCode2, Loader2, Send, Terminal, X} from 'lucide-react'
import {languageLabel, rawSnippetUrl, SnippetEditor, snippetUrl} from '@/components/snippet-editor'
const API_BASE = 'https://snippets.rtast.cn'
async function copyToClipboard(text: string) {
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (err) {
}
}
try {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
if (!successful) throw new Error('execCommand copy failed');
return true;
} catch (err) {
return false;
}
}
export default function Page() {
const [content, setContent] = useState('')
const [filename, setFilename] = useState('untitled.txt')
const [snippetId, setSnippetId] = useState('')
const [status, setStatus] = useState<'idle' | 'loading' | 'error'>('idle')
const [error, setError] = useState('')
const [copied, setCopied] = useState(false)
async function submit(event: FormEvent) {
event.preventDefault()
if (!content.trim()) {
setError('Add some content before publishing.');
setStatus('error');
return
}
setStatus('loading');
setError('');
setSnippetId('')
try {
const response = await fetch(`${API_BASE}/api/v1/snippets`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({content, filename})
})
if (!response.ok) throw new Error(`Request failed with ${response.status}`)
const data = await response.json()
if (!data.snippet_id) throw new Error('The server did not return a snippet_id.')
setSnippetId(data.snippet_id);
setStatus('idle')
} catch (caught) {
setStatus('error');
setError(caught instanceof Error ? caught.message : 'Could not reach the snippet server.')
}
}
async function copyLink() {
if (!snippetId) return
await copyToClipboard(snippetUrl(snippetId));
setCopied(true);
window.setTimeout(() => setCopied(false), 1600)
}
function reset() {
setContent('');
setFilename('untitled.txt');
setSnippetId('');
setError('');
setStatus('idle')
}
return (
<main className="min-h-screen bg-background text-foreground">
<header className="border-b border-border">
<div className="mx-auto flex max-w-6xl items-center justify-between px-5 py-4 lg:px-8">
<a href="/" className="flex items-center gap-3 font-mono text-sm font-semibold tracking-tight"><span
className="grid size-8 place-items-center rounded-lg bg-primary text-primary-foreground"><Terminal
size={16}/></span>KSnippets</a>
</div>
</header>
<div className="mx-auto max-w-6xl px-5 py-10 lg:px-8 lg:py-16">
<form onSubmit={submit}>
<div className="mb-3 flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2 text-sm font-medium"><FileCode2 size={16}
className="text-brand"/> New
snippet
</div>
<div className="flex items-center gap-2"><span
className="rounded-md bg-muted px-2.5 py-1 font-mono text-[11px] text-muted-foreground">{languageLabel(filename)}</span>
<button type="button" onClick={reset}
className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground"
aria-label="Clear editor"><X size={15}/></button>
</div>
</div>
<SnippetEditor value={content} filename={filename} onChange={setContent}/>
<div className="mt-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"><label
className="flex items-center gap-3 text-sm text-muted-foreground"><span
className="font-mono text-xs">filename</span><input value={filename}
onChange={(event) => setFilename(event.target.value || 'untitled.txt')}
className="w-44 border-b border-border bg-transparent py-1 text-foreground outline-none focus:border-brand"/></label>
<button disabled={status === 'loading'}
className="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground transition hover:bg-primary/90 disabled:cursor-wait disabled:opacity-70">{status === 'loading' ?
<Loader2 size={16} className="animate-spin"/> : <Send size={16}/>} Publish snippet
</button>
</div>
</form>
{status === 'error' && <div role="alert"
className="mt-5 rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">{error}</div>}
{snippetId && <section className="mt-8 rounded-xl border border-brand/30 bg-brand/5 p-5">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div><p className="mb-1 text-xs font-medium uppercase tracking-widest text-brand">published
successfully</p><a href={`/${snippetId}`}
className="font-mono text-sm text-foreground underline decoration-brand underline-offset-4">/{snippetId}</a>
</div>
<div className="flex flex-wrap gap-2">
<button type="button" onClick={copyLink}
className="inline-flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 text-xs font-medium hover:bg-muted">{copied ?
<Check size={14}/> : <Copy size={14}/>}{copied ? 'Copied' : 'Copy link'}</button>
<a href={rawSnippetUrl(snippetId)} target="_blank" rel="noreferrer"
className="inline-flex items-center gap-2 rounded-lg bg-primary px-3 py-2 text-xs font-medium text-primary-foreground">Raw <ArrowUpRight
size={14}/></a></div>
</div>
</section>}
</div>
</main>
)
}